如何检查值是否是JavaScript中的对象?


当前回答

这取决于你所说的“是一个物体”。如果您想要所有非原语的内容,即可以设置新财产的内容,那么这应该可以做到:

function isAnyObject(value) {
    return value != null && (typeof value === 'object' || typeof value === 'function');
}

它排除了基元(纯数字/NaN/Infinity、纯字符串、符号、true/false、undefined和null),但其他所有对象(包括Number、Boolean和String对象)都应返回true。注意,JS没有定义当与typeof一起使用时,应该返回哪些“主机”对象,例如窗口或控制台,因此很难用这样的检查来覆盖这些对象。

如果您想知道某个对象是“普通”对象,即它是作为文本{}创建的还是使用object.create(null)创建的,您可以这样做:

function isPlainObject(value) {
    if (Object.prototype.toString.call(value) !== '[object Object]') {
        return false;
    } else {
        var prototype = Object.getPrototypeOf(value);
        return prototype === null || prototype === Object.prototype;
    }
}

编辑2018:因为Symbol.toStringTag现在允许自定义Object.protoct.toString.call(…)的输出,所以上面的isPlainObject函数在某些情况下可能会返回false,即使对象以文本形式开始其生命。可以说,按照惯例,带有自定义字符串标记的对象不再是纯对象,但这进一步模糊了Javascript中的纯对象定义。

其他回答

在阅读并尝试了许多实现之后,我注意到很少有人尝试检查JSON、Math、文档或原型链长度超过1步的对象等值。

我认为,与其检查变量的类型,然后删除边缘事例,不如尽可能简单地进行检查,以避免在添加了注册为“对象”类型的新原语或本地对象时进行重构。

毕竟,typeof运算符会告诉您某个对象是否是JavaScript的对象,但JavaScript对对象的定义对于大多数真实场景来说太宽泛了(例如typeof null==“object”)。下面是一个函数,它通过基本上重复两次检查来确定变量v是否为对象:

只要v的字符串化版本为“[object object]”,就会启动一个循环。我希望函数的结果与下面的日志完全相同,所以这是我最终得出的唯一“对象性”标准。如果失败,函数将立即返回false。v被链中的下一个原型替换为v=Object.getPrototypeOf(v),但也在之后直接求值。当v的新值为null时,这意味着包括根原型(很可能是链中唯一的原型)在内的每个原型都通过了while循环中的检查,我们可以返回true。否则,新的迭代开始。

函数isObj(v){while(Object.product.toString.call(v)=='[Object Object]')if((v=Object.getPrototypeOf(v))==null)返回truereturn false}console.log('FALSE:')console.log('[]->',isObj([]))console.log('ull->',isObj(null))console.log('文档->',isObj(文档))console.log('JSON->',isObj(JSON))console.log('function->',isObj(函数(){}))console.log('newDate()->',isObj(newDate(()))console.log('RegExp->',isObj(/./))console.log('TRUE:')console.log(“{}->”,isObj({}))console.log('newObject()->',isObj(newObject(()))console.log('新对象(null)->',isObj(新对象(空)))console.log('newObject({})->',isObj(newObject({foo:'bar'})))console.log('Object.prototype->',isObj(Object.prototype))console.log('Object.create(null)->',isObj(Object.create(null)))console.log(“Object.create({})->”,isObj(Object.create({foo:'bar'})))console.log(“deep继承->”,isObj(Object.create(Object.create({foo:'bar'}))))

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"

如果您想检查对象的原型是否仅来自object。过滤掉字符串、数字、数组、参数等。

function isObject (n) {
  return Object.prototype.toString.call(n) === '[object Object]';
}

或作为单个表达式箭头函数(ES6+)

const isObject = n => Object.prototype.toString.call(n) === '[object Object]'

您可以使用JSON.stringify来测试Object,如下所示:

var测试={}if(JSON.stringify(测试)[0]==“{”){console.log('这是一个对象')}

如果typeof yourVariable==“object”,则它是一个对象或null。

如果要排除null、数组或函数,只需执行以下操作:

if (
    typeof yourVariable === 'object' &&
    !Array.isArray(yourVariable) &&
    yourVariable !== null
) {
    executeSomeCode();
}