如何检查值是否是JavaScript中的对象?
当前回答
由于对于如何正确处理这个问题似乎有很多困惑,我将留下我的2美分(这个答案符合规范,在任何情况下都会产生正确的结果):
测试原语:未定义的空布尔字符串数
function isPrimitive(o){return typeof o!=='object'||null}
对象不是基本体:
function isObject(o){return !isPrimitive(o)}
或者:
function isObject(o){return o instanceof Object}
function isPrimitive(o){return !isObject(o)}
测试任何阵列:
const isArray=(function(){
const arrayTypes=Object.create(null);
arrayTypes['Array']=true;
arrayTypes['Int8Array']=true;
arrayTypes['Uint8Array']=true;
arrayTypes['Uint8ClampedArray']=true;
arrayTypes['Int16Array']=true;
arrayTypes['Uint16Array']=true;
arrayTypes['Int32Array']=true;
arrayTypes['Uint32Array']=true;
arrayTypes['BigInt64Array']=true;
arrayTypes['BigUint64Array']=true;
arrayTypes['Float32Array']=true;
arrayTypes['Float64Array']=true;
return function(o){
if (!o) return false;
return !isPrimitive(o)&&!!arrayTypes[o.constructor.name];
}
}());
测试对象排除:日期RegExp布尔数字字符串函数任意数组
const isObjectStrict=(function(){
const nativeTypes=Object.create(null);
nativeTypes['Date']=true;
nativeTypes['RegExp']=true;
nativeTypes['Boolean']=true;
nativeTypes['Number']=true;
nativeTypes['String']=true;
nativeTypes['Function']=true;
return function(o){
if (!o) return false;
return !isPrimitive(o)&&!isArray(o)&&!nativeTypes[o.constructor.name];
}
}());
其他回答
如果明确希望检查给定值是否为{}。
function isObject (value) {
return value && typeof value === 'object' && value.constructor === 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"
请记住,new Date()的类型是“object”。
因此,如果要查找{key:value}对象,日期对象是无效的。
最后:o=>o&&typeof o==“对象”&&!在我看来,(o instance of Date)是对你问题的更好回答。
function isObjectLike(value) {
return value != null && typeof value == 'object' && !Array.isArray(value);
}
基于lodash
更新:
这个答案是不完整的,给出了误导性的结果。例如,null也被认为是JavaScript中的对象类型,更不用说其他几种边缘情况。遵循下面的建议,然后转到其他“最支持(和正确!)的答案”:
typeof yourVariable === 'object' && yourVariable !== null
原答覆:
尝试使用typeof(var)和/或var instanceof。
编辑:这个答案给出了如何检查变量财产的思路,但它并不是检查它是否是一个对象的万无一失的方法(毕竟根本没有方法。