如何检查值是否是JavaScript中的对象?
当前回答
确定变量是否为Object的最简单方法:
第一个:评估对象的类型
第二个:从Object获取Array属性必须返回undefined(例如,长度是一个Array属性,它不适用于Object)
so:
if (_object instanceof Object && _object.length === undefined) {
// here you can be sure that you have a curly bracket object :)
}
其他回答
Ramda函数库具有检测JavaScript类型的出色功能。
完整功能的释义:
function type(val) {
return val === null ? 'Null' :
val === undefined ? 'Undefined' :
Object.prototype.toString.call(val).slice(8, -1);
}
当我意识到解决方案是多么简单和美丽时,我不得不笑了。
Ramda文档中的用法示例:
R.type({}); //=> "Object"
R.type(1); //=> "Number"
R.type(false); //=> "Boolean"
R.type('s'); //=> "String"
R.type(null); //=> "Null"
R.type([]); //=> "Array"
R.type(/[A-z]/); //=> "RegExp"
R.type(() => {}); //=> "Function"
R.type(undefined); //=> "Undefined"
我从这个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
考虑-typeof bar==“object”以确定bar是否为对象
虽然typeof bar==“object”是检查bar是否为对象的可靠方法,但JavaScript中令人惊讶的是,null也被视为对象!
因此,令大多数开发人员惊讶的是,以下代码将在控制台中记录true(而不是false):
var bar=空;console.log(类型栏==“对象”);//日志为真!只要意识到这一点,也可以通过检查bar是否为空来轻松避免该问题:
console.log((bar!==null)&&(typeof bar==“object”));//日志错误为了彻底回答,还有两件事值得注意:
首先,如果bar是一个函数,上述解决方案将返回false。在大多数情况下,这是所需的行为,但在希望函数也返回true的情况下,可以将上述解决方案修改为:
console.log((bar!==null)&&((bar类型==“对象”)||(bar类型===“函数”));其次,如果bar是一个数组(例如,如果varbar=[];),上述解决方案将返回true。在大多数情况下,这是所需的行为,因为数组确实是对象,但在您希望数组也为false的情况下,可以将上述解决方案修改为:
console.log((bar!==null)&&(typeof bar==“object”)&&“[对象数组]”);然而,还有另一种方法可以为null、数组和函数返回false,但为对象返回true:
console.log((bar!==null)&&(bar.constructor==Object));或者,如果您正在使用jQuery:
console.log((bar!==null)&&(typeof bar==“object”)&&;
ES5使数组情况非常简单,包括它自己的空检查:
console.log(Array.isArray(bar));
如果您已经在使用AngularJS,那么它有一个内置的方法,可以检查它是否是一个对象(不接受null)。
angular.isObject(...)
您可以使用Object.prototype的toString()方法轻松完成此操作
if(Object.prototype.toString.call(variable) == "[object Object]"){
doSomething();
}
or
if(Object.prototype.toString.call(variable).slice(8,-1).toLowerCase() == "object"){
doSomething();
}