如何检查值是否是JavaScript中的对象?
当前回答
检查值类型的最合理方法似乎是typeof运算符。唯一的问题是它已经严重损坏:
它为null返回“object”,这属于null类型。它为属于Object类型的可调用对象返回“函数”。对于非标准的不可调用对象,它可以返回(几乎)它想要的任何内容。例如,IE似乎喜欢“未知”。唯一被禁止的结果是“函数”和原始类型。
typeof仅对非空基元可靠。因此,检查值是否为对象的一种方法是确保typeof返回的字符串与原语不对应,并且对象不为空。然而,问题是未来的标准可能会引入一种新的原始类型,我们的代码会将其视为一个对象。新类型并不经常出现,但例如ECMAScript 6引入了Symbol类型。
因此,我只推荐结果随值是否为对象而变化的方法,而不是typeof。以下是
测试值是否属于Object类型的正确方法的全面但不详尽的列表。
对象构造函数Object构造函数将传递的参数强制为对象。如果它已经是一个对象,则返回相同的对象。因此,您可以使用它将值强制转换为对象,并将该对象与原始值严格比较。以下函数需要ECMAScript 3,它引入了==:函数isObject(value){/*需要ECMAScript 3或更高版本*/return Object(value)==value;}我喜欢这种方法,因为它简单且自我描述,类似的检查也适用于布尔值、数字和字符串。但是,请注意,它依赖于全局对象,而不是隐藏或更改。施工人员实例化构造函数时,它可以返回一个不同于刚刚创建的实例的值。但该值将被忽略,除非它是一个对象。以下函数需要ECMAScript 3,它允许构造函数返回非对象。在抛出错误的ECMAScript 3之前,try语句当时不存在。函数isObject(value){/*需要ECMAScript 3或更高版本*/return new函数(){return value;}()==value;}虽然比上一个例子简单一点,但这个例子不依赖任何全局属性,因此可能是最安全的。此值旧的ECMAScript规范要求此值为对象。ECMAScript 3引入了Function.prototype.call,它允许调用具有任意此值的函数,但强制为对象。ECMAScript 5引入了一个严格模式,删除了这种行为,但在草率模式下,我们仍然可以(但可以说不应该)依赖它。函数isObject(value){/*需要ECMAScript 3或更高版本处于草率模式*/return函数(){return this==value;}.call(value);}[[原型]]所有普通对象都有一个名为[[Prototype]]的内部槽,其值决定它从哪个其他对象继承。该值只能是对象或null。因此,您可以尝试创建继承自所需值的对象,并检查其是否有效。Object.create和Object.getPrototypeOf都需要ECMAScript 5。函数isObject(value){/*需要ECMAScript 5或更高版本*/尝试{对象.create(value);返回值!==无效的}捕获(错误){return false;}}函数isObject(value){/*需要ECMAScript 5或更高版本*/函数构造函数(){}Constructor.prototype=值;return Object.getPrototypeOf(new Constructor())==值;}一些新的ECMAScript 6方式ECMAScript 6引入了一些新的间接方法来检查值是否为对象。他们使用前面看到的方法将值传递给一些需要对象的代码,该对象封装在try语句中以捕获错误。一些隐藏的例子,不值得评论函数isObject(value){/*需要ECMAScript 6或更高版本*/尝试{Object.setPrototypeOf({},值);返回值!==无效的}捕获(错误){return false;}}函数isObject(value){/*需要ECMAScript 6或更高版本*/尝试{新的WeakSet([value]);返回true;}捕获(错误){return false;}}
注意:我有意跳过了一些方法,例如Object.getPrototypeOf(value)(ES5)和Reflect方法(ES6),因为它们调用了可能会做坏事的基本内部方法,例如,如果value是代理。出于安全原因,我的示例仅引用值,而不直接访问它。
其他回答
让我们在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({})
这取决于你所说的“是一个物体”。如果您想要所有非原语的内容,即可以设置新财产的内容,那么这应该可以做到:
function isAnyObject(value) {
return value != null && (typeof value === 'object' || typeof value === 'function');
}
它排除了基元(纯数字/NaN/Infinity、纯字符串、符号、true/false、undefined和null),但其他所有对象(包括Number、Boolean和String对象)都应返回true。注意,JS没有定义当与typeof一起使用时,应该返回哪些“主机”对象,例如窗口或控制台,因此很难用这样的检查来覆盖这些对象。
如果您想知道某个对象是“普通”对象,即它是作为文本{}创建的还是使用object.create(null)创建的,您可以这样做:
function isPlainObject(value) {
if (Object.prototype.toString.call(value) !== '[object Object]') {
return false;
} else {
var prototype = Object.getPrototypeOf(value);
return prototype === null || prototype === Object.prototype;
}
}
编辑2018:因为Symbol.toStringTag现在允许自定义Object.protoct.toString.call(…)的输出,所以上面的isPlainObject函数在某些情况下可能会返回false,即使对象以文本形式开始其生命。可以说,按照惯例,带有自定义字符串标记的对象不再是纯对象,但这进一步模糊了Javascript中的纯对象定义。
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]))}}
我从这个SO问题中找到了一种“新”方法来进行这种类型检查:为什么instanceof对某些文本返回false?
在此基础上,我创建了一个类型检查函数,如下所示:
function isVarTypeOf(_var, _type){
try {
return _var.constructor === _type;
} catch(ex) {
return false; //fallback for null or undefined
}
}
那么你可以这样做:
console.log(isVarTypeOf('asdf', String)); // returns true
console.log(isVarTypeOf(new String('asdf'), String)); // returns true
console.log(isVarTypeOf(123, String)); // returns false
console.log(isVarTypeOf(123, Number)); // returns true
console.log(isVarTypeOf(new Date(), String)); // returns false
console.log(isVarTypeOf(new Date(), Number)); // returns false
console.log(isVarTypeOf(new Date(), Date)); // returns true
console.log(isVarTypeOf([], Object)); // returns false
console.log(isVarTypeOf([], Array)); // returns true
console.log(isVarTypeOf({}, Object)); // returns true
console.log(isVarTypeOf({}, Array)); // returns false
console.log(isVarTypeOf(null, Object)); // returns false
console.log(isVarTypeOf(undefined, Object)); // returns false
console.log(isVarTypeOf(false, Boolean)); // returns true
这在Chrome 56、Firefox 52、Microsoft Edge 38、Internet Explorer 11和Opera 43上进行了测试
编辑:如果您还想检查变量是否为空或未定义,则可以使用以下方法:
function isVarTypeOf(_var, _type){
try {
return _var.constructor === _type;
} catch(ex) {
return _var == _type; //null and undefined are considered the same
// or you can use === if you want to differentiate them
}
}
var a = undefined, b = null;
console.log(isVarTypeOf(a, undefined)) // returns true
console.log(isVarTypeOf(b, undefined)) // returns true
console.log(isVarTypeOf(a, null)) // returns true
财务评论更新:接受挑战:D
如果要松散比较对象,可以尝试以下方法:
function isVarTypeOf(_var, _type, looseCompare){
if (!looseCompare){
try {
return _var.constructor === _type;
} catch(ex){
return _var == _type;
}
} else {
try{
switch(_var.constructor){
case Number:
case Function:
case Boolean:
case Symbol:
case Date:
case String:
case RegExp:
// add all standard objects you want to differentiate here
return _var.constructor === _type;
case Error:
case EvalError:
case RangeError:
case ReferenceError:
case SyntaxError:
case TypeError:
case URIError:
// all errors are considered the same when compared to generic Error
return (_type === Error ? Error : _var.constructor) === _type;
case Array:
case Int8Array:
case Uint8Array:
case Uint8ClampedArray:
case Int16Array:
case Uint16Array:
case Int32Array:
case Uint32Array:
case Float32Array:
case Float64Array:
// all types of array are considered the same when compared to generic Array
return (_type === Array ? Array : _var.constructor) === _type;
case Object:
default:
// the remaining are considered as custom class/object, so treat it as object when compared to generic Object
return (_type === Object ? Object : _var.constructor) === _type;
}
} catch(ex){
return _var == _type; //null and undefined are considered the same
// or you can use === if you want to differentiate them
}
}
}
这样,你就可以像finance的评论一样:
isVarTypeOf(new (function Foo(){}), Object); // returns false
isVarTypeOf(new (function Foo(){}), Object, true); // returns true
or
Foo = function(){};
Bar = function(){};
isVarTypeOf(new Foo(), Object); // returns false
isVarTypeOf(new Foo(), Object, true); // returns true
isVarTypeOf(new Bar(), Foo, true); // returns false
isVarTypeOf(new Bar(), Bar, true); // returns true
isVarTypeOf(new Bar(), Bar); // returns true
Object.pr原型.toString.call(myVar)将返回:
“[object object]”如果myVar是对象“[object Array]”如果myVar是数组等
有关这方面的更多信息,以及为什么它是typeof的一个很好的替代品,请查看本文。