如何在 JavaScript 中检查对象是否具有特定属性?

2022-08-29 21:58:01

如何在 JavaScript 中检查对象是否具有特定属性?

考虑:

x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
    //Do this
}

这是最好的方法吗?


答案 1

2022年更新

Object.hasOwn()

Object.hasOwn()建议使用,因为它适用于使用并包含已覆盖继承方法的对象创建的对象。虽然可以通过调用外部对象来解决这些问题,但更直观。Object.hasOwnProperty()Object.create(null)hasOwnProperty()Object.prototype.hasOwnProperty()Object.hasOwn()

const object1 = {
  prop: 'exists'
};

console.log(Object.hasOwn(object1, 'prop'));
// expected output: true

原始答案

我真的对给出的答案感到困惑 - 其中大多数都是完全不正确的。当然,您可以具有具有未定义值、null 值或 false 值的对象属性。因此,简单地将财产检查减少到,或者更糟糕的是,会给你完全误导性的结果。typeof this[property]x.key

这取决于你在寻找什么。如果你想知道一个对象是否在物理上包含一个属性(并且它不是来自原型链上的某个地方),那么这就是要走的路。所有现代浏览器都支持它。(在较旧版本的Safari(2.0.1及更早版本)中缺少它,但这些版本的浏览器很少再使用。object.hasOwnProperty

如果你要找的是,如果一个对象上有一个可迭代的属性(当你迭代对象的属性时,它就会出现),那么做:会给你想要的效果。prop in object

由于使用可能是您想要的,并且考虑到您可能需要回退方法,因此我向您提出以下解决方案:hasOwnProperty

var obj = {
    a: undefined,
    b: null,
    c: false
};

// a, b, c all found
for ( var prop in obj ) {
    document.writeln( "Object1: " + prop );
}

function Class(){
    this.a = undefined;
    this.b = null;
    this.c = false;
}

Class.prototype = {
    a: undefined,
    b: true,
    c: true,
    d: true,
    e: true
};

var obj2 = new Class();

// a, b, c, d, e found
for ( var prop in obj2 ) {
    document.writeln( "Object2: " + prop );
}

function hasOwnProperty(obj, prop) {
    var proto = obj.__proto__ || obj.constructor.prototype;
    return (prop in obj) &&
        (!(prop in proto) || proto[prop] !== obj[prop]);
}

if ( Object.prototype.hasOwnProperty ) {
    var hasOwnProperty = function(obj, prop) {
        return obj.hasOwnProperty(prop);
    }
}

// a, b, c found in modern browsers
// b, c found in Safari 2.0.1 and older
for ( var prop in obj2 ) {
    if ( hasOwnProperty(obj2, prop) ) {
        document.writeln( "Object2 w/ hasOwn: " + prop );
    }
}

以上是一个有效的跨浏览器解决方案,但有一个警告:它无法区分原型和实例上存在相同属性的情况 - 它只是假设它来自原型。你可以根据自己的情况把它改得更宽松或更严格,但至少这应该更有帮助。hasOwnProperty()


答案 2

使用Underscore.js或(甚至更好Lodash

_.has(x, 'key');

哪个调用,但(a)键入更短,(b)使用“安全引用”(即即使被覆盖,它也可以工作)。Object.prototype.hasOwnPropertyhasOwnPropertyhasOwnProperty

特别是,Lodash将定义为:_.has

function has(object, key) {
  return object ? hasOwnProperty.call(object, key) : false;
}
// hasOwnProperty = Object.prototype.hasOwnProperty