JavaScript權威指南筆記

字符長度 P39

var p = 'π';
var e = 'e';
var ch = '中';
p.length
e.length
ch.length

在文件不同編碼下,字符長度不同…
GBK下答案爲2/1/2; utf8下爲1/1/1

書中P39中的 例子怎麼實現呢(p.length =>1 e.length => 2)??求告知

布爾值P43

下面的值會轉換成 false

undefined
null
0
-0
NaN
"" //空字符串

對象(包括數組)或轉換成 true

var arr = [];

if (arr) {
    console.log('true');  //輸出true
}
else {
    console.log('false');
}

但是這裏又不對了:

if (arr == false) {
    console.log('arr == false') //輸出了false
}
else {
    console.log('arr != false');
}

原因:

類型轉換

Value String Number Boolean Object
undefined ‘undefined’ NaN false throws TypeError
null ‘null’ 0 false throws TypeError
true ‘true’ 1 new Boolean(true)
false ‘false’ 0 new Boolean(false)
“” (empty string) 0 false new String(“”)
“1.2” (nonempty, numeric) 1.2 true new String(“1.2”)
“one” (nonempty, non-numeric) NaN true new String(“one”)
0 ‘0’ false new Number(0)
-0 ‘0’ false new Number(-0)
NaN ‘undefined’ false new Number(NaN)
Infinity ‘Infinity’ true new Number(Infinity)
-Infinity ‘-Infinity’ true new Number(-Infinity)
1 (finite, non-zero) ‘1’ true new Number(1)
{} (any object) NaN true
[] (empty array) 0 true
[9] (1 numeric elt) ‘9’ 9 true
[‘a’] (any other array) use join() method NaN true
function(){} (any function) ‘undefined’ NaN true
false => 0
[] => 0    [0] => 0

隱性類型轉換步驟


  1. 首先看雙等號前後有沒有NaN,如果存在NaN,一律返回false。
  2. 再看雙等號前後有沒有布爾,有布爾就將布爾轉換爲數字。(false是0,true是1)
  3. 接着看雙等號前後有沒有字符串, 如果是字符串:

  • 對方是對象,對象轉字符串(方法見下面);
  • 對方是數字,字符串轉數字
  • 對方是字符串,直接比較
  • 其他返回false
  • 如果是數字,對方是對象,對象轉數字(方法見下面), 其他一律返回false
  • null, undefined不會進行類型轉換, 但它們倆相等

對象轉字符串

對象轉數字

上圖pdf下載

栗子:

var a;
console.dir(0 == false);//true
console.dir(1 == true);//true
console.dir(2 == {valueOf: function(){return 2}});//true
console.dir(a == NaN);//false
console.dir(NaN == NaN);//false
console.dir(8 == undefined);//false
console.dir(1 == undefined);//false
console.dir(2 == {toString: function(){return 2}});//true
console.dir(undefined == null);//true
console.dir(null == 1);//false
console.dir({ toString:function(){ return 1 } , valueOf:function(){ return [] }} == 1);//true
console.dir(1=="1");//true
console.dir(1==="1");//false

包裝對象 P46

如果引用字符串的屬性,就會將字符串通過new String()轉換成對象,這個對象處理屬性的引用;一旦引用結束,這個新創建的對象就會被銷燬

var s = 'test';
s.len = 4;          // 引用結束立即銷燬
console.log(s.len); // undefined

nullundefined 沒有包裝對象

參考資料:

http://www.haorooms.com/post/js_yinxingleixing
http://www.lookcss.com/js-type/


文章若有紕漏請大家補充指正,謝謝~~

http://blog.xinshangshangxin.com SHANG殤

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章