如何检查值是否是JavaScript中的对象?
当前回答
lodash有isPlainObject,这可能是许多来到这个页面的人都在寻找的。当给定函数或数组时,它返回false。
其他回答
Object.pr原型.toString.call(myVar)将返回:
“[object object]”如果myVar是对象“[object Array]”如果myVar是数组等
有关这方面的更多信息,以及为什么它是typeof的一个很好的替代品,请查看本文。
我有一段代码片段可以使用。当没有给出整段代码时,我觉得很困惑,所以我自己创建了它:
<!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>
usetypeof(myobj)将告诉它是哪种类型的变量。
对于阵列:Array.isArray(inp)或[]是数组的实例
如果是object,将显示“object”
简单的JS函数,
function isObj(v) {
return typeof(v) == "object"
}
Eg:
函数isObj(v){return typeof(v)==“对象”}变量samp_obj={“a”:1,“b”:2,“c”:3}变量num=10;var txt=“您好!”var_collection=[samp_obj,num,txt]for(var_collection中的var i){if(isObj(var_collection[i])){console.log(“是的,它是对象”)}其他{console.log(“No it is”+typeof(var_collection[i]))}}
如果明确希望检查给定值是否为{}。
function isObject (value) {
return value && typeof value === 'object' && value.constructor === Object;
}
好的,在回答问题之前,让我们先给你这个概念,在JavaScript中,函数是Object,也可以是null、Object、Array甚至Date,所以正如你所看到的,没有一种简单的方法像typeof obj==“Object”,所以上面提到的一切都会返回true,但是有一些方法可以通过编写函数或使用JavaScript框架来检查它,好的:
现在,假设您有一个真正的对象(不是null、函数或数组):
var obj = {obj1: 'obj1', obj2: 'obj2'};
纯JavaScript:
//that's how it gets checked in angular framework
function isObject(obj) {
return obj !== null && typeof obj === 'object';
}
or
//make sure the second object is capitalised
function isObject(obj) {
return Object.prototype.toString.call(obj) === '[object Object]';
}
or
function isObject(obj) {
return obj.constructor.toString().indexOf("Object") > -1;
}
or
function isObject(obj) {
return obj instanceof Object;
}
您可以简单地在代码中使用上述函数之一,方法是调用它们,如果它是一个对象,则返回true:
isObject(obj);
如果您使用的是JavaScript框架,他们通常会为您准备这些类型的函数,其中很少:
jQuery:
//It returns 'object' if real Object;
jQuery.type(obj);
角度:
angular.isObject(obj);
Undercore和Lodash:
//(NOTE: in Underscore and Lodash, functions, arrays return true as well but not null)
_.isObject(obj);