在JavaScript的世界里,一切都是對(duì)象。
但是某些對(duì)象還是和其他對(duì)象不太一樣吃溅。為了區(qū)分對(duì)象的類型,我們用typeof操作符獲取對(duì)象的類型鸯檬,它總是返回一個(gè)字符串:
typeof 123; // 'number'
typeof NaN; // 'number'
typeof 'str'; // 'string'
typeof true; // 'boolean'
typeof undefined; // 'undefined'
typeof Math.abs; // 'function'
typeof null; // 'object'
typeof []; // 'object'
typeof {}; // 'object'
可見决侈,number、string喧务、boolean赖歌、function和undefined有別于其他類型。特別注意null的類型是object功茴,Array的類型也是object庐冯,如果我們用typeof將無法區(qū)分出null、Array和通常意義上的object----{}
包裝對(duì)象
除了這些類型外坎穿,JavaScript還提供了包裝對(duì)象展父,熟悉Java的小伙伴肯定很清楚int和Integer這種曖昧關(guān)系。
number玲昧、boolean和string都有包裝對(duì)象栖茉。沒錯(cuò),在JavaScript中孵延,字符串也區(qū)分string類型和它的包裝類型吕漂。包裝對(duì)象用new創(chuàng)建:
var n = new Number(123); // 123,生成了新的包裝類型
var b = new Boolean(true); // true,生成了新的包裝類型
var s = new String('str'); // 'str'生成了新的包裝類型
雖然包裝對(duì)象看上去和原來的值一模一樣,顯示出來的也是一模一樣尘应。但他們的類型已經(jīng)變?yōu)閛bject了惶凝!所以,包裝對(duì)象和原始值用===比較會(huì)返回false:
typeof new Number(123); // 'object'
new Number(123) === 123; // false
typeof new Boolean(true); // 'object'
new Boolean(true) === true; // false
typeof new String('str'); // 'object'
new String('str') === 'str'; // false
<u>所以閑的蛋疼也不要使用包裝對(duì)象犬钢!尤其是針對(duì)string類型2韵省!玷犹!</u>
如果我們?cè)谑褂肗umber坡贺、Boolean和String時(shí),沒有寫new會(huì)發(fā)生什么情況箱舞?
此時(shí),Number()拳亿、Boolean和String()被當(dāng)做普通函數(shù)晴股,把任何類型的數(shù)據(jù)轉(zhuǎn)換為number、boolean和string類型(注意不是其包裝類型):
var n = Number('123'); // 123,相當(dāng)于parseInt()或parseFloat()
typeof n; // 'number'
var b = Boolean('true'); // true
typeof b; // 'boolean'
var b2 = Boolean('false'); // true! 'false'字符串轉(zhuǎn)換結(jié)果為true!因?yàn)樗欠强兆址?var b3 = Boolean(''); // false
var s = String(123.45); // '123.45'
typeof s; // 'string'
是不是感覺頭大了肺魁?這就是JavaScript特有的催眠魅力电湘!
總結(jié)一下,有這么幾條規(guī)則需要遵守:
- 不要使用new Number()、new Boolean()寂呛、new String()創(chuàng)建包裝對(duì)象怎诫;
- 用parseInt()或parseFloat()來轉(zhuǎn)換任意類型到number;
- 用String()來轉(zhuǎn)換任意類型到string,或者直接調(diào)用某個(gè)對(duì)象的toString()方法贷痪;
- 通常不必把任意類型轉(zhuǎn)換為boolean再判斷幻妓,因?yàn)榭梢灾苯訉慽f (myVar) { ... };
- typeof操作符可以判斷出number、boolean劫拢、string肉津、function和undefined;
- 判斷Array要使用Array.isArray(arr);
- 判斷null請(qǐng)使用 myVar === null;
- 判斷某個(gè)全局變量是否存在用typeof window.myVar === 'undefined';
- 函數(shù)內(nèi)部判斷某個(gè)變量是否存在用typeof myVar === 'undefined'舱沧。
最后有細(xì)心的人指出妹沙,任何對(duì)象都有toString()方法嗎?null和undefined就沒有熟吏!確實(shí)如此距糖,這兩個(gè)特殊值除外,雖然null還偽裝成了object類型牵寺。
更有細(xì)心的人指出悍引,number對(duì)象調(diào)用toString()報(bào)SyntaxError:
123.toString(); // SyntaxError
遇到這種情況,要特殊處理一下:
123..toString(); // '123', 注意是兩個(gè)點(diǎn)缸剪!
(123).toString(); // '123'
不要問為什么吗铐,這就是JavaScript代碼的樂趣!