1. 程式人生 > >【js】判斷物件型別

【js】判斷物件型別

對於判斷引數型別

typeof 這個估計是最常用的了 , 比如下面的兩個簡單的例子

typeof {}   // 'object'
typeof /\d/ // 'object'
typeof null // 'object'
typeof undefined // "undefined"

但是,大家上面的例子也看到了,如果我們想具體區分引數到底是 Object 物件還是 null ,使用typeof 是不行的,因為很多型別的返回都是 ‘object’.

大家可以試試下面的方法:

Object.prototype.toString.call(/\d/) // "[object RegExp]"
Object
.prototype.toString.call(null) // "[object Null]" var d = null; d === Object( d ); // false var d = { a:1 } d === Object( d ); // true var d = /\d/ d === Object( d ); // true

更多方法請看 這裡, 還看到一個 效能對比