js判断一个参数是否为对象

var obj = {};

1、toString(推荐),只有当参数为{} 或者 new Object()时才会成立。

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

 

2、constructor,使用该函数也能判断是否是对象,但是当参数为null时,会出现错误。

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) 

 

posted @ 2021-04-26 11:38  IT民工郑小江  阅读(3740)  评论(0编辑  收藏  举报