通過"!!""將非布爾型數(shù)據(jù)隱式轉(zhuǎn)換成布爾型(注意!運算是用于將布爾型的操作數(shù)的邏輯非運算)
> !!'X'; //字符串
< true
> !!1; //Number
< true
> !!0;
< false
> !!'';
< false
> !!null;
< false
> !!Infinity
< true
> !!{} // 進(jìn)行布爾型的數(shù)據(jù)轉(zhuǎn)換時,
< true // Object類型轉(zhuǎn)換后的結(jié)果必定為true
通過使用'+'運算符將Number轉(zhuǎn)換成字符串
> var n = 0;
> n += "";
> typeof n;
< "string"
同樣通過使用'+'運算符將字符串轉(zhuǎn)換成Number
var s = ""; //空字符
console.log(+s); // 0
console.log(typeof +s); //NaN
console.log(parseInt(s)); //NaN
console.log(Number(s)); // 0
var s = " "; //空格符
console.log(+s); // 0
console.log(typeof +s); //NaN
console.log(parseInt(s)); //NaN
console.log(Number(s)); // 0
var s = "abc"; //純字符串
console.log(+s); NaN
console.log(typeof +s); // number
console.log(parseInt(s)); NaN
console.log(Number(s)); NaN
var s = "undefined"; //undefined
console.log(+s); //NaN
console.log(typeof +s); // number
console.log(parseInt(s)); //NaN
console.log(Number(s)); //NaN
var s = "123abc"; // 混合型
console.log(+s); //NaN
console.log(typeof +s); // number
console.log(parseInt(s)); //123
console.log(Number(s)); //NaN
var s = null; //null
console.log(+s); // 0
console.log(typeof +s); // number
console.log(parseInt(s)); NaN
console.log(Number(s)); // 0
不難發(fā)現(xiàn)"+"前置運算符的Number轉(zhuǎn)換規(guī)則和函數(shù)Number()是一樣的,
值得注意的是,Number()將undefined和字符串轉(zhuǎn)換成NaN,NaN同樣是一種
Number類型;同時將null,""(空字符)和" "(空格符)轉(zhuǎn)換成數(shù)字'0'.