如何检查值是否是JavaScript中的对象?
当前回答
让我们在Javascript中定义“对象”。根据MDN文档,每个值都是对象或基元:
基元,基元值不是对象且没有任何方法的数据。JavaScript有7种原始数据类型:string、number、bigint、boolean、undefined、symbol和null。
什么是原始人?
3.“abc”真的无效的未定义
什么是对象(即不是基元)?
对象.原型Object.prototype派生的所有内容功能.原型对象作用函数C(){}--用户定义函数C.prototype——用户定义函数的原型属性:这不是Cs原型new C()--“new”-ing用户定义的函数数学阵列.原型阵列{“a”:1,“b”:2}--使用文字符号创建的对象new Number(3)--基元周围的包装器…许多其他事情。。。对象.create(null)从Object.create(null)派生的所有内容
如何检查值是否为对象
instanceof本身不起作用,因为它忽略了两种情况:
// oops: isObject(Object.prototype) -> false
// oops: isObject(Object.create(null)) -> false
function isObject(val) {
return val instanceof Object;
}
typeof x===“对象”无法工作,因为误报(null)和误报(函数):
// oops: isObject(Object) -> false
function isObject(val) {
return (typeof val === 'object');
}
Object.prototype.toString.call无法工作,因为所有基元都存在误报:
> Object.prototype.toString.call(3)
"[object Number]"
> Object.prototype.toString.call(new Number(3))
"[object Number]"
所以我使用:
function isObject(val) {
if (val === null) { return false;}
return ( (typeof val === 'function') || (typeof val === 'object') );
}
@Daan的回答似乎也奏效:
function isObject(obj) {
return obj === Object(obj);
}
因为根据MDN文档:
Object构造函数为给定值创建对象包装器。如果该值为null或未定义,它将创建并返回一个空对象,否则,它将返回与给定值对应的类型的对象。如果该值已经是一个对象,它将返回该值。
第三种似乎有效的方法(不确定是否100%)是使用Object.getPrototypeOf,如果其参数不是对象,则抛出异常:
// these 5 examples throw exceptions
Object.getPrototypeOf(null)
Object.getPrototypeOf(undefined)
Object.getPrototypeOf(3)
Object.getPrototypeOf('abc')
Object.getPrototypeOf(true)
// these 5 examples don't throw exceptions
Object.getPrototypeOf(Object)
Object.getPrototypeOf(Object.prototype)
Object.getPrototypeOf(Object.create(null))
Object.getPrototypeOf([])
Object.getPrototypeOf({})
其他回答
更新:
这个答案是不完整的,给出了误导性的结果。例如,null也被认为是JavaScript中的对象类型,更不用说其他几种边缘情况。遵循下面的建议,然后转到其他“最支持(和正确!)的答案”:
typeof yourVariable === 'object' && yourVariable !== null
原答覆:
尝试使用typeof(var)和/或var instanceof。
编辑:这个答案给出了如何检查变量财产的思路,但它并不是检查它是否是一个对象的万无一失的方法(毕竟根本没有方法。
哦,我的上帝!我认为这可能比以往任何时候都要短,让我们看看:
短代码和最终代码
函数isObject(obj){返回obj!=null&&obj.constructor.name==“对象”}console.log(isObject({}))//返回trueconsole.log(isObject([]))//返回falseconsole.log(isObject(null))//返回false
解释
退货类型
typeof JavaScript对象(包括null)返回“object”
console.log(类型为null,类型为[],类型为{})
检查其构造函数
检查其构造函数属性会返回带有其名称的函数。
console.log(({}).cconstructor)//返回名为“Object”的函数console.log(([]).cconstructor)//返回名为“Array”的函数console.log((null).cconstructor)//引发错误,因为null实际上没有属性
Function.name简介
Function.name返回函数的只读名称或闭包的“匿名”。
console.log(({}).cconstructor.name)//返回“Object”console.log(([]).cconstructor.name)//返回“Array”console.log((null).cconstructor.name)//引发错误,因为null实际上没有属性
注意:截至2018年,Function.name可能无法在IE中工作https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#Browser_compatibility
出于代码的目的,我找到了与上面的一些答案相对应的决定:
ES6变体:
const checkType = o => Object.prototype
.toString
.call(o)
.replace(/\[|object\s|\]/g, '')
.toLowerCase();
ES5变体:
function checkType(o){
return Object.prototype
.toString
.call(o)
.replace(/\[|object\s|\]/g, '')
.toLowerCase();
}
您可以非常简单地使用它:
checkType([]) === 'array'; // true
checkType({}) === 'object'; // true
checkType(1) === 'number'; // true
checkType('') === 'string'; // true
checkType({}.p) === 'undefined'; // true
checkType(null) === 'null'; // true
等等
var isArray=function(value){
if(Array.isArray){
return Array.isArray(value);
}else{
return Object.prototype.toString.call(value)==='[object Array]';
}
}
var isObject=function(value){
return value !== null&&!isArray(value) && typeof value === 'object';
}
var _val=new Date;
console.log(isObject(_val));//true
console.log(Object.prototype.toString.call(_val)==='[object Object]');//false
有点晚了。。。对于“普通对象”(我的意思是,像{'x':5,'y':7}),我有一个小片段:
function isPlainObject(o) {
return (o === null || Array.isArray(o) || typeof o == 'function' || o.constructor === Date ) ?
false
:(typeof o == 'object');
}
它生成下一个输出:
console.debug(isPlainObject(isPlainObject)); //function, false
console.debug(isPlainObject({'x': 6, 'y': 16})); //literal object, true
console.debug(isPlainObject(5)); //number, false
console.debug(isPlainObject(undefined)); //undefined, false
console.debug(isPlainObject(null)); //null, false
console.debug(isPlainObject('a')); //string, false
console.debug(isPlainObject([])); //array?, false
console.debug(isPlainObject(true)); //bool, false
console.debug(isPlainObject(false)); //bool, false
它总是适用于我。只有当“o”的类型是“object”,但没有null、数组或函数时,If才会返回“true”。:)
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔