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

JavaScript

逆天神奇

2020-03-09

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

考虑:

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

那是最好的方法吗?

第261篇《如何检查对象在JavaScript中是否具有特定属性?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

9个回答
NearSamHarry 2020.03.09

我用这个。如果对象内部有对象,这对我有很大帮助

if(typeof(obj["key"])=="string"){
    alert("property");
}
西里梅 2020.03.09

您可以使用JSON.stringify功能来扭转参考检查。

var obj = {};
// check object
JSON.stringify(obj) == JSON.stringify({}) // return true
村村小小十三 2020.03.09

为什么要使事情变得过于复杂:

var isProperty =  (objectname.keyname || "") ? true : false;

在大多数情况下简单明了...

飞云古一 2020.03.09

您需要使用方法object.hasOwnProperty(property)如果对象具有属性,则返回true,否则返回false。

番长西里神无 2020.03.09

由于存在大规模投票的风险,因此这是针对特定情况的另一种选择。:)

如果要测试对象上的成员,并且想知道它是否已设置为除以下以外的其他值:

  • ''
  • 空值
  • 未定义
  • 0 ...

那么您可以使用:

var foo = {};
foo.bar = "Yes, this is a proper value!";
if (!!foo.bar) {
        // member is set, do something
}
西门Jim 2020.03.09

对象上存在方法“ hasOwnProperty”,但不建议直接调用此方法,因为有时对象可能为null或对象上存在某些属性,例如: { hasOwnProperty: false }

更好的方法是:

// good
var obj = {"bar": "here bar desc"}
console.log(Object.prototype.hasOwnProperty.call(obj, "bar"));

// best
const has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope.
console.log(has.call(obj, "bar"));

小小Itachi 2020.03.09

hasOwnProperty“可用于确定对象是否具有指定属性作为该对象的直接属性;与in运算符不同,此方法不会检查对象的原型链。

因此,最有可能的是,对于您所看到的问题,您不想使用hasOwnProperty,它确定该属性是否以附加方式存在 直接到对象本身而存在

如果要确定属性是否存在于主要要使用的原型链中,例如:

if( prop in object ){ // do something }

我希望这有帮助。

null 2020.03.09
if (typeof x.key != "undefined") {

}

因为

if (x.key)

如果x.key解析false为,则失败(例如x.key = "")。

老丝神无 2020.03.09

我对所给出的答案感到困惑-他们中的大多数都是完全错误的。当然,您可以拥有具有未定义,空值或假值的对象属性。因此,只需将属性检查减少到typeof this[property]甚至更糟,x.key将给您完全误导的结果。

这取决于您要查找的内容。如果您想知道一个对象是否物理上包含一个属性(它不是来自原型链的某个位置),那么object.hasOwnProperty就可以这样做。所有现代的浏览器都支持它。(在Safari的较早版本(2.0.1和更早的版本中不存在),但是那些浏览器版本已经很少使用了。)

如果您要查找的是对象上具有可迭代的属性(当您遍历该对象的属性时,它将出现),则可以这样做: 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,但有一个警告:无法区分原型和实例上具有相同属性的情况-只是假设它来自原型。您可以根据自己的情况将其更改为宽容或严格,但是至少这应该会有所帮助。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android