外观
怎么判断 JavaScript 的类型?
typeof 用来区分大部分原始类型。null 是历史遗留,typeof null === "object"。数组、日期这类对象用 Object.prototype.toString.call,数组优先用 Array.isArray。
原理
原始类型有七种:undefined、null、boolean、number、string、bigint、symbol。其余值都是对象。
typeof 能分清的结果:
js
typeof undefined // "undefined"
typeof 1 // "number"
typeof NaN // "number"
typeof "a" // "string"
typeof true // "boolean"
typeof 10n // "bigint"
typeof Symbol() // "symbol"
typeof function () {} // "function"
typeof null // "object"
typeof [] // "object"函数在 typeof 里单独返回 "function",但它仍然是对象。NaN 的类型是 number。
要分清数组、日期、正则,读取内部标签:
js
Object.prototype.toString.call([]) // "[object Array]"
Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call(new Date) // "[object Date]"instanceof 走原型链:Ctor.prototype 出现在左边对象的原型链上就为真。跨窗口时数组的原型不是当前窗口的 Array.prototype,arr instanceof Array 会失败,所以用 Array.isArray。
new String("a") 是对象,typeof 得到 "object"。字面量 "a" 才是字符串。
追问
== 和 === 差在哪?
=== 不转换类型。== 会做抽象相等:null == undefined 为真,它们和任何其他值比较都为假。对象和原始值比较时,对象先转成原始值。业务代码默认用 ===。要同时接受 null 和 undefined 时,可以写 value == null。
[] == ![] 为什么为真?
![] 是 false。[] == false 时两边都转成数字:空数组先变成空字符串,再变成 0;false 也变成 0。
Object.is 和 === 呢?
两者都是浅比较。差别只在 Object.is(NaN, NaN) 为真,Object.is(+0, -0) 为假。
易错点
typeof null的结果是"object",没有"null"这一档。NaN === NaN为假,判断用Number.isNaN。typeof null、typeof []都是"object",不能靠它区分空值和数组。