js判斷是否爲對象的幾種方法

var obj = {}

1、toString(推薦)

Object.prototype.toString.call(obj) === '[object Object]'

2、constructor

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'

5、$.isPlainObject()
判斷指定參數是否是一個純粹的對象(所謂"純粹的對象",就是該對象是通過"{}"或"new Object"創建的。)

$.isPlainObject(obj) 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章