如何检查值是否是JavaScript中的对象?
当前回答
如果明确希望检查给定值是否为{}。
function isObject (value) {
return value && typeof value === 'object' && value.constructor === Object;
}
其他回答
我有一段代码片段可以使用。当没有给出整段代码时,我觉得很困惑,所以我自己创建了它:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunc()">Try it</button>
<script>
var abc = new Number();
// var abc = 4;
//this is a code variation which will give a diff alert
function myFunc()
{
if(abc && typeof abc === "object")
alert('abc is an object and does not return null value');
else
alert('abc is not an object');
}
</script>
</body>
</html>
const isObject = function(obj) {
const type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
!!obj是检查obj是否正确(以过滤空值)的简写
请记住,new Date()的类型是“object”。
因此,如果要查找{key:value}对象,日期对象是无效的。
最后:o=>o&&typeof o==“对象”&&!在我看来,(o instance of Date)是对你问题的更好回答。
我的上帝,其他答案太混乱了。
简短回答
typeof anyVar==“对象”&&anyVar对象实例&&!(数组的anyVar实例)
要测试这一点,只需在chrome控制台中运行以下语句。
案例1。
var anyVar = {};
typeof anyVar == 'object' && anyVar instanceof Object && !(anyVar instanceof Array) // true
案例2。
anyVar = [];
typeof anyVar == 'object' && anyVar instanceof Object && !(anyVar instanceof Array) // false
案例3。
anyVar = null;
typeof anyVar == 'object' && anyVar instanceof Object && !(anyVar instanceof Array); // false
解释
好吧,我们来分解一下
typeof anyVar==“object”从三个候选项中返回true-[]、{}和null,
anyVar instanceof Object将这些候选对象缩小到两个-[],{}
!(anyVar instanceof Array)仅限于一个-{}
请滚鼓!
至此,您可能已经学会了如何在Javascript中检查Array。
如果您想检查对象的原型是否仅来自object。过滤掉字符串、数字、数组、参数等。
function isObject (n) {
return Object.prototype.toString.call(n) === '[object Object]';
}
或作为单个表达式箭头函数(ES6+)
const isObject = n => Object.prototype.toString.call(n) === '[object Object]'