如何检查值是否是JavaScript中的对象?
当前回答
如果typeof yourVariable==“object”,则它是一个对象或null。
如果要排除null、数组或函数,只需执行以下操作:
if (
typeof yourVariable === 'object' &&
!Array.isArray(yourVariable) &&
yourVariable !== null
) {
executeSomeCode();
}
其他回答
一个基于Matt Fenwick对其完整答案的第三个选项的NodeJS控制台实验。只要稍微调整一下就能判断真假。
以下对象测试返回false。
> if(Object.getPrototypeOf('v') === Object.prototype){console.log(true);}else{console.log(false);}
false
undefined
> if(Object.getPrototypeOf(1) === Object.prototype){console.log(true);}else{console.log(false);}
false
undefined
> if(Object.getPrototypeOf(false) === Object.prototype){console.log(true);}else{console.log(false);}
false
undefined
> if(Object.getPrototypeOf(['apple']) === Object.prototype){console.log(true);}else{console.log(false);}
false
undefined
对象将返回true。
> if(Object.getPrototypeOf({'this':10}) === Object.prototype){console.log(true);}else{console.log(false);}
true
undefined
适用于所有数据类型。它只显示对象
if (data && typeof data === 'object' && !Array.isArray(data)) {
有点晚了。。。对于“普通对象”(我的意思是,像{'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”。:)
这是一个可选链接的答案,也许是这个问题的最小isObj函数。
常量isObj=o=>o?。构造函数==对象;//这是真的console.log(isObj({}));//对象//这些都是假的console.log(isObj(0));//数字console.log(isObj([]));//大堆console.log(isObj('ol'));//一串console.log(isObj(null));//无效的console.log(isObj(未定义));//未定义console.log(isObj(()=>{}));//作用console.log(isObj(对象));//班
试试这个
if (objectName instanceof Object) {
alert('Not an object');
}
else {
alert('An object');
}
推荐文章
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 不可变与可变类型
- 很好的初学者教程socket.io?
- 字符串不能识别为有效的日期时间“格式dd/MM/yyyy”
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?