如何检查值是否是JavaScript中的对象?
当前回答
这取决于用例,如果我们不想让数组和函数成为Object,我们可以使用undercore.js内置函数。
function xyz (obj) {
if (_.isObject(obj) && !_.isFunction(obj) && !_.isArray(obj)) {
// now its sure that obj is an 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({}));//真的
我有一段代码片段可以使用。当没有给出整段代码时,我觉得很困惑,所以我自己创建了它:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunc()">Try it</button>
<script>
var abc = new Number();
// var abc = 4;
//this is a code variation which will give a diff alert
function myFunc()
{
if(abc && typeof abc === "object")
alert('abc is an object and does not return null value');
else
alert('abc is not an object');
}
</script>
</body>
</html>
更新:
这个答案是不完整的,给出了误导性的结果。例如,null也被认为是JavaScript中的对象类型,更不用说其他几种边缘情况。遵循下面的建议,然后转到其他“最支持(和正确!)的答案”:
typeof yourVariable === 'object' && yourVariable !== null
原答覆:
尝试使用typeof(var)和/或var instanceof。
编辑:这个答案给出了如何检查变量财产的思路,但它并不是检查它是否是一个对象的万无一失的方法(毕竟根本没有方法。
可随时使用的检查功能
function isObject(o) {
return null != o &&
typeof o === 'object' &&
Object.prototype.toString.call(o) === '[object Object]';
}
function isDerivedObject(o) {
return !isObject(o) &&
null != o &&
(typeof o === 'object' || typeof o === 'function') &&
/^\[object /.test(Object.prototype.toString.call(o));
}
// Loose equality operator (==) is intentionally used to check
// for undefined too
// Also note that, even null is an object, within isDerivedObject
// function we skip that and always return false for null
解释
在Javascript中,null、Object、Array、Date和函数都是对象。虽然,null有点做作。因此,最好先检查空值,以检测它是否为空。检查o==“object”的类型可确保o是一个对象。如果不进行此检查,Object.prototype.toString将毫无意义,因为它将返回任何对象,即使是未定义和null!例如:toString(undefined)返回[object undefined]!在typeofo=='object'检查之后,toString.call(o)是一个很好的方法来检查o是一个对象,还是一个派生对象,如Array、Date或函数。在isDerivedObject函数中,它检查o是否为函数。因为,函数也是一个对象,这就是它存在的原因。若并没有这样做,函数将返回false。示例:isDerivedObject(function(){})将返回false,但现在返回true。人们总是可以改变对象的定义。因此,可以相应地更改这些函数。
测验
函数isObject(o){返回null!=o&&typeof o==“对象”&&Object.pr原型.toString.call(o)==“[对象对象]”;}函数isDerivedObject(o){回来isObject(o)&&空!=o&&(类型o==“对象”| |类型o===“函数”)&&/^\[object/.test(object.protype.toString.call(o));}//测试//null是对象吗?控制台日志('是空的对象吗?',isObject(空));控制台日志('是否为null派生对象?',isDerivedObject(空));//1234是一个对象吗?控制台日志('1234是对象吗?',isObject(1234));控制台日志('1234是派生对象吗?',isDerivedObject(1234));//新编号(1234)是对象吗?控制台日志('新编号(1234)是对象吗?',isObject(新编号(1234)));控制台日志('新编号(1234)是派生对象吗?',isDerivedObject(1234));//函数对象是对象吗?控制台日志('是(new(function(){}))对象吗?',isObject((new(函数(){})));控制台日志(“(new(function(){}))是派生对象吗?”,isObject((new(函数(){})));//{}是对象吗?控制台日志(“是{}对象吗?”,isObject({}));控制台日志(“{}是派生对象吗?”,isDerivedObject({}));//Array是对象吗?控制台日志('数组是对象吗?',isObject([]))控制台日志('数组是派生对象吗?',isDerivedObject([]))//Date是对象吗?控制台日志('日期是对象吗?',isObject(新日期()));控制台日志('日期是派生对象吗?',isDerivedObject(新日期()));//函数是对象吗?控制台日志('函数是对象吗?',isObject(函数(){}));控制台日志('函数是派生对象吗?',isDerivedObject(函数(){}));
由于对于如何正确处理这个问题似乎有很多困惑,我将留下我的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];
}
}());