如何检查值是否是JavaScript中的对象?
当前回答
我从这个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
其他回答
有点晚了。。。对于“普通对象”(我的意思是,像{'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”。:)
检查值类型的最合理方法似乎是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是代理。出于安全原因,我的示例仅引用值,而不直接访问它。
如果您已经在使用AngularJS,那么它有一个内置的方法,可以检查它是否是一个对象(不接受null)。
angular.isObject(...)
简单的工作解决方案:
function isObject(value) {
return !(value instanceof Date) && !Array.isArray(value) && !Object.is(value, null) && !Object.is(value, undefined) && !(value instanceof Function)
}
lodash有isPlainObject,这可能是许多来到这个页面的人都在寻找的。当给定函数或数组时,它返回false。