const obj = { }
1.toString(推薦)
Object.prototype.toString.call(obj) === '[object Object]'
2.constructor
obj.constructor === Object obj?.constructor === Object
3.instanceof 需要注意的是由於數組也是對象,因此用 arr instanceof Object 也為true。
obj instanceof Object
4.運算符 typeof
typeof obj === Object
// 根據typeof判斷對象也不太准確
表達式 返回值
typeof undefined 'undefined'
typeof null 'object'
typeof true 'boolean'
typeof 123 'number'
typeof "abc" 'string'
typeof function() {} 'function'
typeof {} 'object'
typeof [] 'object'
檢測數組類型幾種方法
function isArrayFn (o) {
return Object.prototype.toString.call(o) === '[object Array]';
}
Object.prototype.toString的行為:首先,取得對象的一個內部屬性[[Class]],然后依據這個屬性,返回一個類似於"[object Array]"的字符串作為結果
(看過ECMA標准的應該都知道,[[]]用來表示語言內部用到的、外部不可直接訪問的屬性,稱為“內部屬性”)。
利用這 個方法,再配合call,我們可以取得任何對象的內部屬性[[Class]],然后把類型檢測轉化為字符串比較,以達到我們的目的。
2.Array.isArray()
ECMAScript5將Array.isArray()正式引入JavaScript,目的就是准確地檢測一個值是否為數組。IE9+、 Firefox 4+、Safari 5+、Opera 10.5+和Chrome都實現了這個方法。但是在IE8之前的版本是不支持的。