如何检查值是否是JavaScript中的对象?
当前回答
这取决于用例,如果我们不想让数组和函数成为Object,我们可以使用undercore.js内置函数。
function xyz (obj) {
if (_.isObject(obj) && !_.isFunction(obj) && !_.isArray(obj)) {
// now its sure that obj is an object
}
}
其他回答
我喜欢用这个
function isObject (obj) {
return typeof(obj) == "object"
&& !Array.isArray(obj)
&& obj != null
&& obj != ""
&& !(obj instanceof String) }
我认为在大多数情况下,Date必须作为Object通过检查,因此我不会过滤掉日期
我从这个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
当其他一切都失败时,我使用这个:
var isObject = function(item) {
return item.constructor.name === "Object";
};
通过逆向选择的不同方法:
我回顾了这里的所有答案,但仍然缺少一种不同的方法。根据MDN文档,JavaScript中的对象是非原始值。基本值:
布尔型Null类型未定义的类型数字类型BigInt类型字符串类型符号类型
基于这一事实,以下方法正在实施逆向选择:
//根据MDN文档检查值是否为原始值:函数为PrimitiveValue(value){返回(值类型==“符号”||类型值==“字符串”||值类型==“数字”||类型值==“boolean”||类型值==“未定义”||值==空||类型值==“bigint”);};//检查输入是否不是原始值,因此对象:函数isObject(输入){if(isPrimitiveValue(输入)){return false;}返回true;};console.log(isObject(10));//假的console.log(isObject(〔{foo:“bar”}〕));//真的console.log(isObject({a:1,b:2,c:3}));//真的console.log(isObject(Object.getPrototypeOf(“foo”));//真的console.log(isObject(符号(“foo”));//假的console.log(isObject(BigInt(9007199254740991));//假的console.log(isObject(null));//假的console.log(isObject(未定义));//假的console.log(isObject(false));//假的console.log(isObject({}));//真的
我的上帝,其他答案太混乱了。
简短回答
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。
推荐文章
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 不可变与可变类型
- 很好的初学者教程socket.io?
- 字符串不能识别为有效的日期时间“格式dd/MM/yyyy”
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?