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

考虑:

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

这是最好的方法吗?


当前回答

表演

今天2020.12.17,我在Chrome v87、Safari v13.1.2和Firefox v83上对MacOs HighSierra 10.13.6进行了测试,以确定所选的解决方案。

后果

我只比较解决方案A-F,因为它们给出了详细信息部分片段中使用的所有大小写的有效结果。适用于所有浏览器

基于(A)的解决方案是快速或最快的解决方案(E)对于大型对象的chrome最快,对于小型数组的firefox最快,如果键不存在对于小型阵列,解决方案(F)最快(比其他解决方案快10倍以上)解决方案(D,E)非常快基于洛沙的溶液(B)是最慢的

细节

我执行4个测试用例:

当对象有10个字段并且搜索到的关键字存在时,您可以在此处运行它当对象有10个字段并且搜索的关键字不存在时,您可以在此处运行它当对象有10000个字段并且搜索到的关键字存在时,您可以在此处运行它当对象有10000个字段并且搜索到的关键字存在时,您可以在此处运行它

下面的代码片段显示了解决方案之间的差异A.BCDEFGH我JK

//所以https://stackoverflow.com/q/135448/860099//第三节:https://stackoverflow.com/a/14664748/860099函数A(x){返回x中的“key”}//第三节:https://stackoverflow.com/a/11315692/860099函数B(x){return _.has(x,'key')}//第三节:https://stackoverflow.com/a/40266120/860099函数C(x){return Reflect.has(x,'key')}//第三节:https://stackoverflow.com/q/135448/860099函数D(x){return x.hasOwnProperty('key')}//第三节:https://stackoverflow.com/a/11315692/860099函数E(x){return Object.pr原型.hasOwnProperty.call(x,'key')}//第三节:https://stackoverflow.com/a/136411/860099函数F(x){函数hasOwnProperty(obj,prop){var proto=obj.__proto__||obj.constructor.prototype;return(obj中的prop)&&(!(proto中的prop)||proto[prop]!==obj[prop]);}return hasOwnProperty(x,'key')}//第三节:https://stackoverflow.com/a/135568/860099函数G(x){返回类型(x.key)!=='未定义'}//第三节:https://stackoverflow.com/a/22740939/860099函数H(x){返回x.key!==未定义}//第三节:https://stackoverflow.com/a/38332171/860099函数I(x){回来x键}//第三节:https://stackoverflow.com/a/41184688/860099函数J(x){回来x[“键”]}//第三节:https://stackoverflow.com/a/54196605/860099函数K(x){返回布尔值(x.key)}// --------------------//测试// --------------------设x1={‘key‘:1};设x2={'key':“1”};让x3={'key':true};让x4={'key':[]};让x5={‘key‘:{}};让x6={'key':()=>{}};让x7={'key':“”};让x8={'key':0};让x9={'key':false};let x10={'key':未定义};设x11={“否”:1};设b=x=>x?1:0;控制台日志(“1 2 3 4 5 6 7 8 9 10 11”);[A,B,C,D,E,F,G,H,I,J,K]映射(F=>{控制台日志(`${f.name}${b(f(x1))}$(f(x2))}}${b(f(x3))}{$(b(f)x4)}${(f(x5))}${f(f(x6)))}${b(f(x7))〕}$}b((f(x8))`)})console.log('\nLegend:列(案例)');console.log('1.key=1');console.log('2.key=“1”');console.log('3.key=true');console.log('4.key=[]');console.log('5.key={}');console.log('6.key=()=>{}');console.log('7.key=“”');console.log('8.key=0');console.log('9.key=false');console.log('10.key=未定义');console.log('11.no key');<script src=“https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js“integrity=”sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==“crossrorigin=”匿名“></script>此shippet只显示性能测试中使用的函数,而不执行测试本身!

下面是铬的示例结果

其他回答

2022年更新

Object.hasOwn()

建议使用Object.hasOwn()而不是Object.hasOwnerProperty(),因为它适用于使用Object.create(null)创建的对象以及已重写继承的hasOwnProperty()方法的对象。虽然可以通过对外部对象调用Object.pr原型.hasOwnProperty()来解决这些问题,但Object.hasOwn()更直观。

实例

const object1 = {
  prop: 'exists'
};

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

原答覆

我真的被给出的答案弄糊涂了——大多数答案都是完全错误的。当然,您可以拥有具有未定义、null或false值的对象财产。因此,简单地将属性检查减少为this〔property〕的类型,或者更糟糕的是,x.key将给您带来完全误导的结果。

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

如果您要查找的是一个对象上是否有可迭代的属性(当您迭代对象的财产时,它就会出现),那么在对象中执行:prop将获得您想要的效果。

由于使用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()的一个有效的跨浏览器解决方案,但有一个警告:它无法区分原型和实例上相同属性的情况-它只是假设它来自原型。根据你的情况,你可以把它改得更宽或更严,但至少这应该更有帮助。

带反射的ECMAScript 6解决方案。创建如下包装:

/**
Gets an argument from array or object.
The possible outcome:
- If the key exists the value is returned.
- If no key exists the default value is returned.
- If no default value is specified an empty string is returned.
@param obj    The object or array to be searched.
@param key    The name of the property or key.
@param defVal Optional default version of the command-line parameter [default ""]
@return The default value in case of an error else the found parameter.
*/
function getSafeReflectArg( obj, key, defVal) {
   "use strict";
   var retVal = (typeof defVal === 'undefined' ? "" : defVal);
   if ( Reflect.has( obj, key) ) {
       return Reflect.get( obj, key);
   }
   return retVal;
}  // getSafeReflectArg

迭代对象自身财产的更好方法:

如果要在不使用hasOwnProperty()检查的情况下迭代对象的财产,用于(let key of Object.keys(stud)){}方法:

for(let key of Object.keys(stud)){
  console.log(key); // will only log object's Own properties
}

完整示例并与hasOwnProperty()中的for进行比较

function Student() {
  this.name = "nitin";
}

Student.prototype = {
  grade: 'A'
}

let stud = new Student();

// for-in approach
for(let key in stud){
  if(stud.hasOwnProperty(key)){
    console.log(key); // only outputs "name"
  }
} 

//Object.keys() approach
for(let key of Object.keys(stud)){
  console.log(key);
}

也可以使用ES6 Reflect对象:

x = {'key': 1};
Reflect.has( x, 'key'); // returns true

Reflect.has的MDN文档可在此处找到。

静态Reflect.has()方法的工作方式类似于函数中的in运算符。

if (x.key !== undefined)

Armin Ronacher似乎已经击败了我,但是:

Object.prototype.hasOwnProperty = function(property) {
    return this[property] !== undefined;
};

x = {'key': 1};

if (x.hasOwnProperty('key')) {
    alert('have key!');
}

if (!x.hasOwnProperty('bar')) {
    alert('no bar!');
}

康拉德·鲁道夫(Konrad Rudolph)和阿明·罗纳彻(Armin Ronacher)指出,一个更安全但更慢的解决方案是:

Object.prototype.hasOwnProperty = function(property) {
    return typeof this[property] !== 'undefined';
};