简体   繁体   English

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

[英]How do I check if an object has a specific property in JavaScript?

How do I check if an object has a specific property in JavaScript?如何检查 object 在 JavaScript 中是否具有特定属性?

Consider:考虑:

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

Is that the best way to do it?这是最好的方法吗?


2022 UPDATE 2022 更新


Rather than add another answer to the one million repeated answers, I am just going to tack on to the top rated answer here that there is another option as of 2022与其在 100 万个重复的答案中添加另一个答案,我只想在这里添加评分最高的答案,即截至2022 年还有另一个选择

Object.hasOwn()

There's no need to reinvent the wheel, so I'll give you the [MDN version][1]:没有必要重新发明轮子,所以我给你[MDN版本][1]:

Object.hasOwn() is recommended over Object.hasOwnProperty() because it works for objects created using Object.create(null) and with objects that have overridden the inherited hasOwnProperty() method.推荐使用 Object.hasOwn( Object.hasOwn()而不是Object.hasOwnProperty() ,因为它适用于使用 Object.create(null) 创建的对象以及覆盖了继承的 hasOwnProperty() 方法的对象。 While it is possible to workaround these problems by calling Object.prototype.hasOwnProperty() on an external object, Object.hasOwn() is more intuitive.虽然可以通过在外部对象上调用Object.prototype.hasOwnProperty()来解决这些问题,但Object.hasOwn()更直观。

Ill add to the above by saying that it also looks syntactically cleaner.我补充说它在语法上看起来也更干净。


John Resig's Answer:约翰·雷西格的回答:


I'm really confused by the answers that have been given - most of them are just outright incorrect.我真的对给出的答案感到困惑——其中大多数都是完全不正确的。 Of course you can have object properties that have undefined, null, or false values.当然,您可以拥有具有 undefined、null 或 false 值的对象属性。 So simply reducing the property check to typeof this[property] or, even worse, x.key will give you completely misleading results.因此,简单地将属性检查减少到typeof this[property]或者更糟糕的是, x.key会给你带来完全误导的结果。

It depends on what you're looking for.这取决于你在寻找什么。 If you want to know if an object physically contains a property (and it is not coming from somewhere up on the prototype chain) then object.hasOwnProperty is the way to go.如果你想知道一个对象物理上是否包含一个属性(并且它不是来自原型链上的某个地方),那么object.hasOwnProperty是要走的路。 All modern browsers support it.所有现代浏览器都支持它。 (It was missing in older versions of Safari - 2.0.1 and older - but those versions of the browser are rarely used any more.) (旧版本的 Safari - 2.0.1 和更早版本 - 但这些版本的浏览器已很少使用了。)

If what you're looking for is if an object has a property on it that is iterable (when you iterate over the properties of the object, it will appear) then doing: prop in object will give you your desired effect.如果您要查找的是对象是否具有可迭代的属性(当您迭代对象的属性时,它将出现),那么执行: prop in object将为您提供所需的效果。

Since using hasOwnProperty is probably what you want, and considering that you may want a fallback method, I present to you the following solution:由于使用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 );
    }
}

The above is a working, cross-browser, solution to hasOwnProperty , with one caveat: It is unable to distinguish between cases where an identical property is on the prototype and on the instance - it just assumes that it's coming from the prototype.以上是hasOwnProperty的一个可行的跨浏览器解决方案,但有一个警告:它无法区分原型和实例上的相同属性的情况 - 它只是假设它来自原型。 You could shift it to be more lenient or strict, based upon your situation, but at the very least this should be more helpful.您可以根据您的情况将其更改为更宽松或更严格,但至少这应该更有帮助。

With Underscore.js or ( even better ) Lodash :使用Underscore.js或( 甚至更好Lodash

_.has(x, 'key');

Which calls Object.prototype.hasOwnProperty , but (a) is shorter to type, and (b) uses "a safe reference to hasOwnProperty " (ie it works even if hasOwnProperty is overwritten).它调用Object.prototype.hasOwnProperty ,但 (a) 类型更短,并且 (b) 使用“对hasOwnProperty的安全引用”(即,即使hasOwnProperty被覆盖,它也可以工作)。

In particular, Lodash defines _.has as:特别是,Lodash 将_.has定义为:

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

Use:利用:

 var x = { 'key': 1 }; if ('key' in x) { console.log('has'); }

Note : the following is nowadays largely obsolete thanks to strict mode, and hasOwnProperty .注意:由于严格模式和hasOwnProperty ,以下内容如今已基本过时。 The correct solution is to use strict mode and to check for the presence of a property using obj.hasOwnProperty .正确的解决方案是使用严格模式并使用obj.hasOwnProperty检查属性是否存在。 This answer predates both these things, at least as widely implemented (yes, it is that old).这个答案早于这两件事,至少被广泛实施(是的,它已经那么老了)。 Take the following as a historical note.将以下内容作为历史记录。


Bear in mind that undefined is (unfortunately) not a reserved word in JavaScript if you're not using strict mode.请记住,如果您不使用严格模式,那么undefined (不幸的是)不是JavaScript 中的保留字。 Therefore, someone (someone else, obviously) could have the grand idea of redefining it, breaking your code.因此,某人(显然是其他人)可能有重新定义它的宏伟想法,从而破坏您的代码。

A more robust method is therefore the following:因此,更稳健的方法如下:

if (typeof(x.attribute) !== 'undefined')

On the flip side, this method is much more verbose and also slower.另一方面,这种方法更冗长,也更慢。 :-/ :-/

A common alternative is to ensure that undefined is actually undefined, eg by putting the code into a function which accepts an additional parameter, called undefined , that isn't passed a value.一种常见的替代方法是确保undefined实际上是未定义的,例如,通过将代码放入一个函数中,该函数接受一个名为undefined的附加参数,该参数未传递值。 To ensure that it's not passed a value, you could just call it yourself immediately, eg:为确保它没有传递值,您可以立即自己调用它,例如:

(function (undefined) {
    … your code …
    if (x.attribute !== undefined)
        … mode code …
})();
if (x.key !== undefined)

Armin Ronacher seems to have already beat me to it , but: 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!');
}

A safer, but slower solution, as pointed out by Konrad Rudolph and Armin Ronacher would be:正如Konrad RudolphArmin Ronacher 所指出的,一个更安全但更慢的解决方案是:

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

Considering the following object in Javascript考虑 Javascript 中的以下对象

const x = {key: 1};

You can use the in operator to check if the property exists on an object:您可以使用in运算符检查对象上是否存在该属性:

console.log("key" in x);

You can also loop through all the properties of the object using a for - in loop, and then check for the specific property:您还可以使用for - in -in 循环遍历对象的所有属性,然后检查特定属性:

for (const prop in x) {
    if (prop === "key") {
        //Do something
    }
}

You must consider if this object property is enumerable or not, because non-enumerable properties will not show up in a for-in loop.您必须考虑此对象属性是否可枚举,因为不可枚举的属性不会出现在for-in循环中。 Also, if the enumerable property is shadowing a non-enumerable property of the prototype, it will not show up in Internet Explorer 8 and earlier.此外,如果可枚举属性遮蔽了原型的不可枚举属性,则它不会出现在Internet Explorer 8和更早版本中。

If you'd like a list of all instance properties, whether enumerable or not, you can use如果您想要所有实例属性的列表,无论是否可枚举,您都可以使用

Object.getOwnPropertyNames(x);

This will return an array of names of all properties that exist on an object.这将返回对象上存在的所有属性的名称数组。

Reflections provide methods that can be used to interact with Javascript objects. 反射提供了可用于与 Javascript 对象交互的方法。 The static Reflect.has() method works like the in operator as a function.静态Reflect.has()方法的工作方式类似于 in 运算符作为函数。

console.log(Reflect.has(x, 'key'));
// expected output: true

console.log(Reflect.has(x, 'key2'));
// expected output: false

console.log(Reflect.has(object1, 'toString'));
// expected output: true

Finally, you can use the typeof operator to directly check the data type of the object property:最后,您可以使用 typeof 运算符直接检查对象属性的数据类型:

if (typeof x.key === "undefined") {
    console.log("undefined");
}

If the property does not exist on the object, it will return the string undefined.如果对象上不存在该属性,它将返回未定义的字符串。 Else it will return the appropriate property type.否则它将返回适当的属性类型。 However, note that this is not always a valid way of checking if an object has a property or not, because you could have a property that is set to undefined, in which case, using typeof x.key would still return true (even though the key is still in the object).但是,请注意,这并不总是检查对象是否具有属性的有效方法,因为您可以将属性设置为 undefined,在这种情况下,使用typeof x.key仍会返回 true(即使钥匙仍在对象中)。

Similarly, you can check if a property exists by comparing directly to the undefined Javascript property同样,您可以通过直接与undefined的 Javascript 属性进行比较来检查属性是否存在

if (x.key === undefined) {
    console.log("undefined");
}

This should work unless key was specifically set to undefined on the x object这应该可以工作,除非在 x 对象上明确将 key 设置为undefined

Let's cut through some confusion here.让我们在这里消除一些混乱。 First, let's simplify by assuming hasOwnProperty already exists;首先,让我们假设hasOwnProperty已经存在来简化; this is true of the vast majority of current browsers in use.当前使用的绝大多数浏览器都是如此。

hasOwnProperty returns true if the attribute name that is passed to it has been added to the object.如果传递给它的属性名称已添加到对象, hasOwnProperty返回 true。 It is entirely independent of the actual value assigned to it which may be exactly undefined .它完全独立于分配给它的实际值,可能完全是undefined

Hence:因此:

var o = {}
o.x = undefined

var a = o.hasOwnProperty('x')  // a is true
var b = o.x === undefined // b is also true

However:然而:

var o = {}

var a = o.hasOwnProperty('x')  // a is now false
var b = o.x === undefined // b is still true

The problem is what happens when an object in the prototype chain has an attribute with the value of undefined?问题是当原型链中的对象具有值为 undefined 的属性时会发生什么? hasOwnProperty will be false for it, and so will !== undefined . hasOwnProperty对它来说是假的, !== undefined也是如此。 Yet, for..in will still list it in the enumeration.然而, for..in仍然会在枚举中列出它。

The bottom line is there is no cross-browser way (since Internet Explorer doesn't expose __prototype__ ) to determine that a specific identifier has not been attached to an object or anything in its prototype chain.底线是没有跨浏览器的方式(因为 Internet Explorer 不公开__prototype__ )来确定特定标识符尚未附加到对象或其原​​型链中的任何内容。

If you are searching for a property, then "no" .如果您正在搜索属性,那么"no" You want:你要:

if ('prop' in obj) { }

In general, you should not care whether or not the property comes from the prototype or the object.通常,您不应该关心属性是来自原型还是来自对象。

However, because you used 'key' in your sample code, it looks like you are treating the object as a hash, in which case your answer would make sense.但是,因为您在示例代码中使用了 'key',所以看起来您将对象视为哈希,在这种情况下,您的答案是有意义的。 All of the hashes keys would be properties in the object, and you avoid the extra properties contributed by the prototype.所有哈希键都是对象中的属性,您可以避免原型贡献的额外属性。

John Resig's answer was very comprehensive, but I thought it wasn't clear. John Resig 的回答非常全面,但我认为并不清楚。 Especially with when to use "'prop' in obj".尤其是何时在 obj 中使用“'prop'”。

For testing simple objects, use:要测试简单对象,请使用:

if (obj[x] !== undefined)

If you don't know what object type it is, use:如果您不知道它是什么对象类型,请使用:

if (obj.hasOwnProperty(x))

All other options are slower...所有其他选项都较慢...

Details细节

A performance evaluation of 100,000,000 cycles under Node.js to the five options suggested by others here:对 Node.js 下 100,000,000 次循环的性能评估,这里有其他人建议的五个选项:

function hasKey1(k,o) { return (x in obj); }
function hasKey2(k,o) { return (obj[x]); }
function hasKey3(k,o) { return (obj[x] !== undefined); }
function hasKey4(k,o) { return (typeof(obj[x]) !== 'undefined'); }
function hasKey5(k,o) { return (obj.hasOwnProperty(x)); }

The evaluation tells us that unless we specifically want to check the object's prototype chain as well as the object itself, we should not use the common form :评估告诉我们,除非我们特别想检查对象的原型链以及对象本身,否则我们不应该使用通用形式

if (X in Obj)...

It is between 2 to 6 times slower depending on the use case根据用例,速度会慢 2 到 6 倍

hasKey1 execution time: 4.51 s
hasKey2 execution time: 0.90 s
hasKey3 execution time: 0.76 s
hasKey4 execution time: 0.93 s
hasKey5 execution time: 2.15 s

Bottom line, if your Obj is not necessarily a simple object and you wish to avoid checking the object's prototype chain and to ensure x is owned by Obj directly, use if (obj.hasOwnProperty(x))... .底线,如果您的 Obj 不一定是一个简单的对象,并且您希望避免检查对象的原型链并确保 x 直接归 Obj 所有,请使用if (obj.hasOwnProperty(x))...

Otherwise, when using a simple object and not being worried about the object's prototype chain, using if (typeof(obj[x]) !== 'undefined')... is the safest and fastest way.否则,在使用简单对象而不担心对象的原型链时,使用if (typeof(obj[x]) !== 'undefined')...是最安全、最快的方法。

If you use a simple object as a hash table and never do anything kinky, I would use if (obj[x])... as I find it much more readable.如果您使用一个简单的对象作为哈希表并且从不做任何古怪的事情,我会使用if (obj[x])...因为我发现它更具可读性。

Yes it is :) I think you can also do Object.prototype.hasOwnProperty.call(x, 'key') which should also work if x has a property called hasOwnProperty :)是的:)我认为你也可以做Object.prototype.hasOwnProperty.call(x, 'key')如果x有一个名为hasOwnProperty的属性,它也应该工作 :)

But that tests for own properties.但这会测试自己的属性。 If you want to check if it has an property that may also be inhered you can use typeof x.foo != 'undefined' .如果您想检查它是否具有也可能被继承的属性,您可以使用typeof x.foo != 'undefined'

if(x.hasOwnProperty("key")){
  // …
}

because因为

if(x.key){
  // …
}

fails if x.key is falsy (for example, x.key === "" ).如果x.key是假的(例如, x.key === "" ),则失败。

You can also use the ES6 Reflect object :你也可以使用ES6 Reflect对象

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

Documentation on MDN for Reflect.has can be found here .可以在此处找到有关Reflect.has的 MDN 文档。

The static Reflect.has() method works like the in operator as a function.静态Reflect.has()方法的工作方式类似于in 运算符作为函数。

Do not do this object.hasOwnProperty(key)) .不要这样做object.hasOwnProperty(key)) It's really bad because these methods may be shadowed by properties on the object in question - consider { hasOwnProperty: false } - or, the object may be a null object (Object.create(null)) .这真的很糟糕,因为这些方法可能会被相关对象的属性所掩盖 - 考虑{ hasOwnProperty: false } - 或者,该对象可能是一个空对象(Object.create(null))

The best way is to do Object.prototype.hasOwnProperty.call(object, key) or:最好的方法是执行Object.prototype.hasOwnProperty.call(object, key)或:

const has = Object.prototype.hasOwnProperty; // Cache the lookup once, in module scope.
console.log(has.call(object, key));
/* Or */
import has from 'has'; // https://www.npmjs.com/package/has
console.log(has(object, key));

OK, it looks like I had the right answer unless if you don't want inherited properties:好的,除非您不想要继承的属性,否则我似乎有正确的答案:

if (x.hasOwnProperty('key'))

Here are some other options to include inherited properties:以下是包含继承属性的其他一些选项:

if (x.key) // Quick and dirty, but it does the same thing as below.

if (x.key !== undefined)

Another relatively simple way is using Object.keys .另一种相对简单的方法是使用Object.keys This returns an array which means you get all of the features of an array.这将返回一个array ,这意味着您可以获得数组的所有功能。

var noInfo = {};
var info = {something: 'data'};

Object.keys(noInfo).length //returns 0 or false
Object.keys(info).length //returns 1 or true

Although we are in a world with great browser support.尽管我们所处的世界拥有强大的浏览器支持。 Because this question is so old I thought I'd add this: This is safe to use as of JavaScript v1.8.5 .因为这个问题太老了,我想我会添加这个:从JavaScript v1.8.5 开始,这是安全的。

JavaScript is now evolving and growing as it now has good and even efficient ways to check it. JavaScript 现在正在发展和成长,因为它现在有很好的甚至有效的方法来检查它。

Here are some easy ways to check if object has a particular property :以下是检查对象是否具有特定属性的一些简单方法:

  1. Using hasOwnProperty()使用hasOwnProperty()
const hero = {
  name: 'Batman'
};

hero.hasOwnProperty('name');     // => true
hero.hasOwnProperty('realName'); // => false
  1. Using keyword/operator in在中使用关键字/运算in
const hero = {
  name: 'Batman'
};

'name' in hero;     // => true
'realName' in hero; // => false
  1. Comparing with undefined keywordundefined的关键字比较
const hero = {
  name: 'Batman'
};

hero.name;     // => 'Batman'
hero.realName; // => undefined

// So consider this
hero.realName == undefined // => true (which means property does not exists in object)
hero.name == undefined // => false (which means that property exists in object)

For more information, check here .如需更多信息,请查看此处

hasOwnProperty "can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator , this method does not check down the object's prototype chain." hasOwnProperty “可用于确定对象是否具有指定属性作为该对象的直接属性;与 in 运算符不同,此方法不会向下检查对象的原型链。”

So most probably, for what seems by your question, you don't want to use hasOwnProperty, which determines if the property exists as attached directly to the object itself ,.因此,最有可能的是,对于您的问题,您不想使用 hasOwnProperty,它确定属性是否直接附加到对象本身

If you want to determine if the property exists in the prototype chain, you may want to use it like:如果您想确定该属性是否存在于原型链中,您可能希望像这样使用它:

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

You can use the following approaches-您可以使用以下方法 -

var obj = {a:1}
console.log('a' in obj)               // 1
console.log(obj.hasOwnProperty('a'))  // 2
console.log(Boolean(obj.a))         // 3

The difference between the following approaches are as follows-以下方法之间的区别如下 -

  1. In the first and third approach we are not just searching in object but its prototypal chain too.在第一种和第三种方法中,我们不仅在对象中搜索,而且也在其原型链中进行搜索。 If the object does not have the property, but the property is present in its prototype chain it is going to give true.如果对象没有该属性,但该属性存在于它的原型链中,它将给出 true。

 var obj = { a: 2, __proto__ : {b: 2} } console.log('b' in obj) console.log(Boolean(obj.b))

  1. The second approach will check only for its own properties.第二种方法将仅检查其自身的属性。 Example -例子 -

 var obj = { a: 2, __proto__ : {b: 2} } console.log(obj.hasOwnProperty('b'))

  1. The difference between the first and the third is if there is a property which has value undefined the third approach is going to give false while first will give true.第一种和第三种方法的区别在于,如果有一个属性的值未定义,第三种方法将给出假,而第一种方法将给出真。

 var obj = { b : undefined } console.log(Boolean(obj.b)) console.log('b' in obj);

Performance表现

Today 2020.12.17 I perform tests on MacOs HighSierra 10.13.6 on Chrome v87, Safari v13.1.2 and Firefox v83 for chosen solutions.今天 2020.12.17,我在 Chrome v87、Safari v13.1.2 和 Firefox v83 上对 MacOs HighSierra 10.13.6 进行测试,以选择解决方案。

Results结果

I compare only solutions AF because they give valid result for all cased used in snippet in details section.我只比较解决方案 AF,因为它们为详细信息部分的片段中使用的所有大小写提供了有效结果。 For all browsers适用于所有浏览器

  • solution based on in (A) is fast or fastest基于(A) in的解决方案是快速或最快的
  • solution (E) is fastest for chrome for big objects and fastest for firefox for small arrays if key not exists解决方案(E)对于大对象的 chrome 是最快的,如果 key 不存在,对于小数组的 firefox 是最快的
  • solution (F) is fastest (~ >10x than other solutions) for small arrays对于小型阵列,解决方案 (F) 最快(~ > 10 倍于其他解决方案)
  • solutions (D,E) are quite fast解决方案(D,E)非常快
  • solution based on losash has (B) is slowest基于 losash 的解决has (B) 最慢

在此处输入图像描述

Details细节

I perform 4 tests cases:我执行 4 个测试用例:

  • when object has 10 fields and searched key exists - you can run it HERE当对象有 10 个字段并且搜索到的键存在时 - 你可以在这里运行它
  • when object has 10 fields and searched key not exists - you can run it HERE当对象有 10 个字段并且搜索到的键不存在时 - 您可以在此处运行它
  • when object has 10000 fields and searched key exists - you can run it HERE当对象有 10000 个字段并且存在搜索到的键时 - 您可以在此处运行它
  • when object has 10000 fields and searched key exists - you can run it HERE当对象有 10000 个字段并且存在搜索到的键时 - 您可以在此处运行它

Below snippet presents differences between solutions A B C D E F G H I J K下面的片段显示了解决方案A B C D E F G H I J K之间的差异

 // SO https://stackoverflow.com/q/135448/860099 // src: https://stackoverflow.com/a/14664748/860099 function A(x) { return 'key' in x } // src: https://stackoverflow.com/a/11315692/860099 function B(x) { return _.has(x, 'key') } // src: https://stackoverflow.com/a/40266120/860099 function C(x) { return Reflect.has( x, 'key') } // src: https://stackoverflow.com/q/135448/860099 function D(x) { return x.hasOwnProperty('key') } // src: https://stackoverflow.com/a/11315692/860099 function E(x) { return Object.prototype.hasOwnProperty.call(x, 'key') } // src: https://stackoverflow.com/a/136411/860099 function F(x) { function hasOwnProperty(obj, prop) { var proto = obj.__proto__ || obj.constructor.prototype; return (prop in obj) && (!(prop in proto) || proto[prop] !== obj[prop]); } return hasOwnProperty(x,'key') } // src: https://stackoverflow.com/a/135568/860099 function G(x) { return typeof(x.key) !== 'undefined' } // src: https://stackoverflow.com/a/22740939/860099 function H(x) { return x.key !== undefined } // src: https://stackoverflow.com/a/38332171/860099 function I(x) { return !!x.key } // src: https://stackoverflow.com/a/41184688/860099 function J(x) { return !!x['key'] } // src: https://stackoverflow.com/a/54196605/860099 function K(x) { return Boolean(x.key) } // -------------------- // TEST // -------------------- let x1 = {'key': 1}; let x2 = {'key': "1"}; let x3 = {'key': true}; let x4 = {'key': []}; let x5 = {'key': {}}; let x6 = {'key': ()=>{}}; let x7 = {'key': ''}; let x8 = {'key': 0}; let x9 = {'key': false}; let x10= {'key': undefined}; let x11= {'nokey': 1}; let b= x=> x ? 1:0; console.log(' 1 2 3 4 5 6 7 8 9 10 11'); [A,B,C,D,E,F,G,H,I,J,K ].map(f=> { console.log( `${f.name} ${b(f(x1))} ${b(f(x2))} ${b(f(x3))} ${b(f(x4))} ${b(f(x5))} ${b(f(x6))} ${b(f(x7))} ${b(f(x8))} ${b(f(x9))} ${b(f(x10))} ${b(f(x11))} ` )}) console.log('\nLegend: Columns (cases)'); 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 = undefined '); console.log('11. no-key ');
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script> This shippet only presents functions used in performance tests - it not perform tests itself!

And here are example results for chrome这是 chrome 的示例结果

在此处输入图像描述

Given myObject object and “myKey” as key name:给定myObject对象和“myKey”作为键名:

Object.keys(myObject).includes('myKey')

or或者

myObject.hasOwnProperty('myKey')

or或者

typeof myObject.myKey !== 'undefined'

The last was widely used, but (as pointed out in other answers and comments) it could also match on keys deriving from Object prototype.最后一个被广泛使用,但是(正如其他答案和评论中指出的那样)它也可以匹配从 Object 原型派生的键。

Here is another option for a specific case.这是针对特定情况的另一种选择。 :) :)

If you want to test for a member on an object and want to know if it has been set to something other than:如果您想测试对象上的成员并想知道它是否已设置为以下内容:

  • '' ''
  • false错误的
  • null无效的
  • undefined不明确的
  • 0 ... 0 ...

then you can use:那么你可以使用:

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

some easier and short options depending on the specific use case:根据特定用例的一些更简单和简短的选项:

  1. to check if the property exists, regardless of value, use the in operator ("a" in b)要检查属性是否存在,无论值如何,请使用in 运算符(b 中的“a”)
  2. to check a property value from a variable, use bracket notation (obj[v])要检查变量的属性值,请使用括号表示法 (obj[v])
  3. to check a property value as truthy, use optional chaining (?.)要检查属性值是否真实,请使用可选链接 (?.)
  4. to check a property value boolean, use double-not / bang-bang / (!!)要检查属性值布尔值,请使用double-not / bang-bang / (!!)
  5. to set a default value for null / undefined check, use nullish coalescing operator (??)要为 null / undefined 检查设置默认值,请使用nullish 合并运算符 (??)
  6. to set a default value for falsey value check, use short-circuit logical OR operator (||)要为错误值检查设置默认值,请使用短路逻辑 OR 运算符 (||)

run the code snippet to see results:运行代码片段以查看结果:

 let obj1 = {prop:undefined}; console.log(1,"prop" in obj1); console.log(1,obj1?.prop); let obj2 = undefined; //console.log(2,"prop" in obj2); would throw because obj2 undefined console.log(2,"prop" in (obj2 ?? {})) console.log(2,obj2?.prop); let obj3 = {prop:false}; console.log(3,"prop" in obj3); console.log(3,!!obj3?.prop); let obj4 = {prop:null}; let look = "prop" console.log(4,"prop" in obj4); console.log(4,obj4?.[look]); let obj5 = {prop:true}; console.log(5,"prop" in obj5); console.log(5,obj5?.prop === true); let obj6 = {otherProp:true}; look = "otherProp" console.log(6,"prop" in obj6); console.log(6,obj6.look); //should have used bracket notation let obj7 = {prop:""}; console.log(7,"prop" in obj7); console.log(7,obj7?.prop || "empty");

I see very few instances where hasOwn is used properly, especially given its inheritance issues我看到很少有正确使用hasOwn的实例,尤其是考虑到它的继承问题

现在有了ECMAScript22 ,我们可以使用hasOwn而不是hasOwnProperty (因为这个特性有缺陷)

Object.hasOwn(obj, propKey)

An ECMAScript 6 solution with reflection.带有反射的 ECMAScript 6 解决方案。 Create a wrapper like:创建一个包装器,如:

/**
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

There is a method, "hasOwnProperty", that exists on an object, but it's not recommended to call this method directly, because it might be sometimes that the object is null or some property exist on the object like: { hasOwnProperty: false }有一个方法,“hasOwnProperty”,存在于对象上,但不建议直接调用此方法,因为有时对象可能为 null 或对象上存在某些属性,例如: { hasOwnProperty: false }

So a better way would be:所以更好的方法是:

 // 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"));

You need to use the method object.hasOwnProperty(property) .您需要使用方法object.hasOwnProperty(property) It returns true if the object has the property and false if the object doesn't.如果对象具有该属性,则返回 true;如果对象没有,则返回 false。

Showing how to use this answer展示如何使用这个答案

const object= {key1: 'data', key2: 'data2'};

Object.keys(object).includes('key1') //returns true

We can use indexOf as well, I prefer includes我们也可以使用indexOf ,我更喜欢include

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it). hasOwnProperty()方法返回一个布尔值,指示对象是否具有指定的属性作为它自己的属性(而不是继承它)。

const object1 = {};
object1.property1 = 42;

console.log(object1.hasOwnProperty('property1'));
// expected output: true

console.log(object1.hasOwnProperty('toString'));
// expected output: false

console.log(object1.hasOwnProperty('hasOwnProperty'));
// expected output: false

Know more 了解更多

Don't over-complicate things when you can do:当你可以做的时候,不要把事情过度复杂化:

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

It Is simple and clear for most cases...对于大多数情况来说,这很简单明了......

A Better approach for iterating on object's own properties:迭代对象自身属性的更好方法:

If you want to iterate on object's properties without using hasOwnProperty() check, use for(let key of Object.keys(stud)){} method:如果您想在不使用hasOwnProperty()检查的情况下迭代对象的属性,请使用for(let key of Object.keys(stud)){}方法:

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

full Example and comparison with for-in with hasOwnProperty()完整的示例和与for-in with hasOwnProperty()比较

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);
}

With all these answers, I think the best new school way of doing it is.有了所有这些答案,我认为最好的新学校方式是。

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

It avoids all other porotype searching and just goes with what the object has.它避免了所有其他 porotype 搜索,只与对象所具有的匹配。 It also doesn't have issue with Eslint. Eslint 也没有问题。

如果 x.key 存在,x?.key 返回 1,否则未定义

How do I check if an object has a specific property in JavaScript?如何在 JavaScript 中检查对象是否具有特定属性?

Consider:考虑:

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

Is that the best way to do it?这是最好的方法吗?

i used this. 我用这个。 which is lots helped me if you have a objects inside object 如果对象内部有对象,这对我有很大帮助

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检查 JavaScript 对象是否具有以特定字符串开头的属性名称? - How to check if a JavaScript Object has a property name that starts with a specific string? 如何检查 object 是否只有一个属性或只有两个属性而 javascript 中没有其他属性 - How do I check if an object has only one property or only two properties and no other property in javascript 如何在Javascript中检查对象或其子/子对象是否具有属性/键? - How do I check to see if an object or its children/sub-objects has a property/key in Javascript? 如何安全检查对象是否具有属性或方法? - How do I safely check if an object has a property or a method? 如何检查javascript对象是否具有某个属性 - How to check if a javascript object has a certain property javascript-如何检查对象是否为特定属性 - javascript- How to check if an object as a specific property 如何在javascript / jquery中动态检查对象的子对象/属性 - How do I dynamically check an object for a subobject/property in javascript/jquery 如何检查Javascript全局对象是否已被篡改? - How do I check if the Javascript global object has been tampered with? 如何使对象的特定属性在javascript中不可变? - How do I make a specific property of an object immutable in javascript? 如何检查数组是否具有具有特定属性的 object,然后找到该属性? - How do I check if an array has an object with a certain property and then find that property?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM