如何检查一个对象是否具有JavaScript属性?

时间:2021-04-14 07:28:39

How do I check if an object has a property in JavaScript?

如何检查一个对象是否具有JavaScript属性?

Consider:

考虑:

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

Is that the best way to do it?

这是最好的方法吗?

22 个解决方案

#1


1172  

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. So simply reducing the property check to typeof this[property] or, even worse, x.key will give you completely misleading results.

我真的对已经给出的答案感到困惑——大多数答案都是完全错误的。当然,您可以拥有未定义、null或错误值的对象属性。因此,只需将属性检查简化为这种(属性)或更糟糕的x。关键会给你完全误导的结果。

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. 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.

如果您正在寻找的是一个对象在其上有一个可迭代的属性(当您迭代对象的属性时,它将出现)然后做: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. You could shift it to be more lenient or strict, based upon your situation, but at the very least this should be more helpful.

上面是一个工作的、跨浏览器的、针对hasOwnProperty的解决方案,有一个警告:它不能区分在原型上和实例上相同属性的情况——它只是假设它来自原型。根据你的情况,你可以让它变得更加宽松或严格,但至少这应该更有帮助。

#2


228  

With Underscore.js or (even better) lodash:

与强调。js或者(更好的)lodash:

_.has(x, 'key');

Which calls Object.prototype.hasOwnProperty, but (a) is shorter to type, and (b) uses "a safe reference to hasOwnProperty" (i.e. it works even if hasOwnProperty is overwritten).

Object.prototype的电话。hasOwnProperty,但是(a)是更短的类型,(b)使用“对hasOwnProperty的安全引用”(即,即使hasOwnProperty被覆盖,它也可以工作)。

In particular, lodash defines _.has as:

特别是,lodash定义了_。如:

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

#3


97  

Note: the following is nowadays largely obsolete thanks to strict mode, and hasOwnProperty. The correct solution is to use strict mode and to check for the presence of a property using 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.

注意:由于严格的模式和hasOwnProperty,现在已经基本过时了。正确的解决方案是使用严格的模式,并检查是否存在使用object . hasownproperty的属性。这个答案早在这两件事之前就有了,至少是被广泛地执行了(是的,它是旧的)。把以下这些作为历史记录。


Bear in mind that undefined is (unfortunately) not a reserved word in JavaScript if you’re not using strict mode. Therefore, someone (someone else, obviously) could have the grand idea of redefining it, breaking your code.

请记住,如果不使用严格的模式,未定义的是(不幸的)JavaScript中没有保留字。因此,某人(显然是其他人)可能有重新定义它的伟大想法,破坏你的代码。

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, e.g. by putting the code into a function which accepts an additional parameter, called undefined, that isn’t passed a value. To ensure that it’s not passed a value, you could just call it yourself immediately, e.g.:

一个常见的替代方法是确保未定义的定义实际上是未定义的,例如将代码放入一个函数中,该函数接受一个未定义的附加参数,该参数没有传递一个值。为了确保它没有传递一个值,您可以直接自己调用它,例如:

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

#4


86  

What about?

关于什么?

var x = {'key': 1};

if ('key' in x) {
    console.log('has');
}

#5


35  

if (x.key !== undefined)

Armin Ronacher seems to have already beat me to it, but:

阿尔芒·罗彻似乎已经把我打败了,但是:

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 Rudolph和Armin Ronacher所指出的那样,一个更安全但更缓慢的解决方案是:

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

#6


30  

You can use the in operator to check if the property exists on an object:

您可以使用in操作符检查对象上是否存在属性:

x = {'key': 1};
alert("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循环遍历对象的所有属性,然后检查特定属性:

for (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. 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.

您必须考虑该对象属性是否是可枚举的,因为不可枚举属性将不会出现在in -in循环中。另外,如果可枚举属性隐藏了原型的不可枚举属性,那么它将不会出现在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.

这将返回一个对象上存在的所有属性的数组。

Finally, you can use the typeof operator to directly check the data type of the object property:

最后,您可以使用typeof操作符直接检查对象属性的数据类型:

if (typeof x.key == "undefined") {
    alert("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).

如果该属性在对象上不存在,它将返回未定义的字符串。否则它将返回适当的属性类型。但是,请注意,这并不总是检查对象是否具有属性的有效方法,因为您可以拥有一个设置为未定义的属性,在这种情况下,使用typeof x。键仍然返回true(即使键仍然在对象中)。

Update: You can check if a property exists by comparing to the undefined javascript property

更新:您可以通过与未定义的javascript属性进行比较来检查是否存在属性。

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

This should work unless key was specifically set to undefined on the x object

除非在x对象上设置了未定义的键,否则这个操作应该有效。

#7


18  

Let's cut through some confusion here. First, let's simplify by assuming hasOwnProperty already exists; this is true of the vast majority of current browsers in use.

让我们在这里讨论一些困惑。首先,让我们简化一下,假设hasOwnProperty已经存在;这适用于当前使用的绝大多数浏览器。

hasOwnProperty returns true if the attribute name that is passed to it has been added to the object. It is entirely independent of the actual value assigned to it which may be exactly undefined.

如果将传递给它的属性名称添加到对象中,则hasOwnProperty将返回true。它完全独立于分配给它的实际值,它可能完全没有定义。

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? hasOwnProperty will be false for it, and so will !== undefined. Yet, for..in will still list it in the enumeration.

问题是,当原型链中的对象具有未定义值的属性时,会发生什么情况?hasOwnProperty将是错误的,因此将!==未定义。然而,对. .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__)来确定一个特定的标识符没有被连接到一个对象或它的原型链中的任何东西。

#8


13  

If you are searching for a property, then "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. All of the hashes keys would be properties in the object, and you avoid the extra properties contributed by the prototype.

但是,由于您在示例代码中使用了“key”,所以看起来您将对象视为散列,在这种情况下,您的答案将是有意义的。所有的散列键都是对象中的属性,您可以避免原型所提供的额外属性。

John Resig's answer was very comprehensive, but I thought it wasn't clear. Especially with when to use "'prop' in obj".

John Resig的回答非常全面,但我认为还不清楚。特别是在obj中使用“‘道具’”的时候。

#9


12  

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

}

Because

因为

if (x.key)

fails if x.key resolves to false (for example, x.key = "").

失败如果x。密钥解析为false(例如,x)。关键= " ")。

#10


11  

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。调用(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 ! =“定义”。

#11


7  

You can also use the ES6 Reflect object:

你也可以使用ES6反射对象:

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

Documentation on MDN for Reflect.has can be found here.

关于MDN的文档说明。在这里可以找到。

The static Reflect.has() method works like the in operator as a function.

方法的作用类似于操作符作为函数。

#12


6  

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)

#13


6  

For testing simple objects use: if (obj[x] !== undefined)

用于测试简单对象使用:if (obj[x] !==未定义)

If you don't know what object type it is use: if (obj.hasOwnProperty(x))

如果您不知道它的对象类型是什么:If (object . hasownproperty (x))

All other options are slower..

所有其他选项都比较慢。

Details

细节

Performance evaluation of 100,000,000 cycles under Nodejs to the 5 options suggested by others here:

在Nodejs下的100,000,000个周期的性能评估到其他的5个选项:

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

评估告诉我们,除非我们特别想要检查对象的原型链以及对象本身,否则我们不应该使用公共形式:if (X in Obj)…根据用例,它的速度慢2到6倍。

hasKey1 execution time: 4s 510.427785ms
hasKey2 execution time: 0s 904.374806ms
hasKey3 execution time: 0s 760.336193ms
hasKey4 execution time: 0s 935.19901ms
hasKey5 execution time: 2s 148.189608ms

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 (object . 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 (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])…因为我觉得它可读性更强。

Have fun.

玩得开心。

#14


5  

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“可以用来确定对象是否具有指定的属性作为该对象的直接属性;与操作符不同,该方法不会检查对象的原型链。

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 main want to use in, like:

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

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

I hope this helps.

我希望这可以帮助。

#15


3  

Another relatively simple way is using Object.keys. This returns an array which means you get all of the features of an array.

另一种相对简单的方法是使用Object.keys。这将返回一个数组,这意味着您将获得一个数组的所有特性。

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 JS v1.8.5

尽管我们身处一个拥有强大浏览器支持的世界。因为这个问题太老了,我想我应该加上这个:这是安全使用的JS v1.8.5。

#16


2  

With risk of massive downvoting, 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
}

#17


2  

ECMA Script 6 solution with reflect. Create wrapper like:

ECMA脚本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

#18


1  

You can also use this open source reusable component I wrote called object-hasOwnProperty.

您还可以使用我编写的名为object-hasOwnProperty的开源可重用组件。

Example:

例子:

hasOwnProperty({foo: 'bar'}, 'foo') // => true
hasOwnProperty({foo: 'bar'}, 'bar') // => false

It's quite simple:

很简单:

function hasOwnProperty(obj: {}, prop: string|number): boolean {
  return Object.prototype.hasOwnProperty.call(obj, prop);
};

#19


1  

You need to use the method object.hasOwnProperty(property). It returns true if the object has the property and false if the object doesn't.

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

#20


0  

If the key you are checking is stored in a variable, you can check it like this:

如果您正在检查的密钥存储在一个变量中,您可以这样检查它:

x = {'key': 1};
y = 'key';
x[y];

#21


0  

There is method "hasOwnProperty" exists on object, but its not recommended to call this method directly because might be sometimes the object is null or some property exist on object like: { hasOwnProperty: false }

在对象上存在方法“hasOwnProperty”,但不建议直接调用该方法,因为有时对象为null,或者对象上存在一些属性:{hasOwnProperty: false}

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

#22


0  

Do not do this object.hasOwnProperty(key)), its 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(key)),它真的很糟糕,因为这些方法可能会被问题上的对象的属性所跟踪—考虑{hasOwnProperty: false}—或者,对象可能是null对象(object. create(null))。

The best way is to do Object.prototype.hasOwnProperty.call(object, key) or:

最好的方法是做Object.prototype.hasOwnProperty。(对象、关键)或:

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

#1


1172  

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. So simply reducing the property check to typeof this[property] or, even worse, x.key will give you completely misleading results.

我真的对已经给出的答案感到困惑——大多数答案都是完全错误的。当然,您可以拥有未定义、null或错误值的对象属性。因此,只需将属性检查简化为这种(属性)或更糟糕的x。关键会给你完全误导的结果。

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. 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.

如果您正在寻找的是一个对象在其上有一个可迭代的属性(当您迭代对象的属性时,它将出现)然后做: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. You could shift it to be more lenient or strict, based upon your situation, but at the very least this should be more helpful.

上面是一个工作的、跨浏览器的、针对hasOwnProperty的解决方案,有一个警告:它不能区分在原型上和实例上相同属性的情况——它只是假设它来自原型。根据你的情况,你可以让它变得更加宽松或严格,但至少这应该更有帮助。

#2


228  

With Underscore.js or (even better) lodash:

与强调。js或者(更好的)lodash:

_.has(x, 'key');

Which calls Object.prototype.hasOwnProperty, but (a) is shorter to type, and (b) uses "a safe reference to hasOwnProperty" (i.e. it works even if hasOwnProperty is overwritten).

Object.prototype的电话。hasOwnProperty,但是(a)是更短的类型,(b)使用“对hasOwnProperty的安全引用”(即,即使hasOwnProperty被覆盖,它也可以工作)。

In particular, lodash defines _.has as:

特别是,lodash定义了_。如:

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

#3


97  

Note: the following is nowadays largely obsolete thanks to strict mode, and hasOwnProperty. The correct solution is to use strict mode and to check for the presence of a property using 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.

注意:由于严格的模式和hasOwnProperty,现在已经基本过时了。正确的解决方案是使用严格的模式,并检查是否存在使用object . hasownproperty的属性。这个答案早在这两件事之前就有了,至少是被广泛地执行了(是的,它是旧的)。把以下这些作为历史记录。


Bear in mind that undefined is (unfortunately) not a reserved word in JavaScript if you’re not using strict mode. Therefore, someone (someone else, obviously) could have the grand idea of redefining it, breaking your code.

请记住,如果不使用严格的模式,未定义的是(不幸的)JavaScript中没有保留字。因此,某人(显然是其他人)可能有重新定义它的伟大想法,破坏你的代码。

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, e.g. by putting the code into a function which accepts an additional parameter, called undefined, that isn’t passed a value. To ensure that it’s not passed a value, you could just call it yourself immediately, e.g.:

一个常见的替代方法是确保未定义的定义实际上是未定义的,例如将代码放入一个函数中,该函数接受一个未定义的附加参数,该参数没有传递一个值。为了确保它没有传递一个值,您可以直接自己调用它,例如:

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

#4


86  

What about?

关于什么?

var x = {'key': 1};

if ('key' in x) {
    console.log('has');
}

#5


35  

if (x.key !== undefined)

Armin Ronacher seems to have already beat me to it, but:

阿尔芒·罗彻似乎已经把我打败了,但是:

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 Rudolph和Armin Ronacher所指出的那样,一个更安全但更缓慢的解决方案是:

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

#6


30  

You can use the in operator to check if the property exists on an object:

您可以使用in操作符检查对象上是否存在属性:

x = {'key': 1};
alert("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循环遍历对象的所有属性,然后检查特定属性:

for (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. 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.

您必须考虑该对象属性是否是可枚举的,因为不可枚举属性将不会出现在in -in循环中。另外,如果可枚举属性隐藏了原型的不可枚举属性,那么它将不会出现在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.

这将返回一个对象上存在的所有属性的数组。

Finally, you can use the typeof operator to directly check the data type of the object property:

最后,您可以使用typeof操作符直接检查对象属性的数据类型:

if (typeof x.key == "undefined") {
    alert("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).

如果该属性在对象上不存在,它将返回未定义的字符串。否则它将返回适当的属性类型。但是,请注意,这并不总是检查对象是否具有属性的有效方法,因为您可以拥有一个设置为未定义的属性,在这种情况下,使用typeof x。键仍然返回true(即使键仍然在对象中)。

Update: You can check if a property exists by comparing to the undefined javascript property

更新:您可以通过与未定义的javascript属性进行比较来检查是否存在属性。

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

This should work unless key was specifically set to undefined on the x object

除非在x对象上设置了未定义的键,否则这个操作应该有效。

#7


18  

Let's cut through some confusion here. First, let's simplify by assuming hasOwnProperty already exists; this is true of the vast majority of current browsers in use.

让我们在这里讨论一些困惑。首先,让我们简化一下,假设hasOwnProperty已经存在;这适用于当前使用的绝大多数浏览器。

hasOwnProperty returns true if the attribute name that is passed to it has been added to the object. It is entirely independent of the actual value assigned to it which may be exactly undefined.

如果将传递给它的属性名称添加到对象中,则hasOwnProperty将返回true。它完全独立于分配给它的实际值,它可能完全没有定义。

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? hasOwnProperty will be false for it, and so will !== undefined. Yet, for..in will still list it in the enumeration.

问题是,当原型链中的对象具有未定义值的属性时,会发生什么情况?hasOwnProperty将是错误的,因此将!==未定义。然而,对. .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__)来确定一个特定的标识符没有被连接到一个对象或它的原型链中的任何东西。

#8


13  

If you are searching for a property, then "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. All of the hashes keys would be properties in the object, and you avoid the extra properties contributed by the prototype.

但是,由于您在示例代码中使用了“key”,所以看起来您将对象视为散列,在这种情况下,您的答案将是有意义的。所有的散列键都是对象中的属性,您可以避免原型所提供的额外属性。

John Resig's answer was very comprehensive, but I thought it wasn't clear. Especially with when to use "'prop' in obj".

John Resig的回答非常全面,但我认为还不清楚。特别是在obj中使用“‘道具’”的时候。

#9


12  

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

}

Because

因为

if (x.key)

fails if x.key resolves to false (for example, x.key = "").

失败如果x。密钥解析为false(例如,x)。关键= " ")。

#10


11  

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。调用(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 ! =“定义”。

#11


7  

You can also use the ES6 Reflect object:

你也可以使用ES6反射对象:

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

Documentation on MDN for Reflect.has can be found here.

关于MDN的文档说明。在这里可以找到。

The static Reflect.has() method works like the in operator as a function.

方法的作用类似于操作符作为函数。

#12


6  

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)

#13


6  

For testing simple objects use: if (obj[x] !== undefined)

用于测试简单对象使用:if (obj[x] !==未定义)

If you don't know what object type it is use: if (obj.hasOwnProperty(x))

如果您不知道它的对象类型是什么:If (object . hasownproperty (x))

All other options are slower..

所有其他选项都比较慢。

Details

细节

Performance evaluation of 100,000,000 cycles under Nodejs to the 5 options suggested by others here:

在Nodejs下的100,000,000个周期的性能评估到其他的5个选项:

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

评估告诉我们,除非我们特别想要检查对象的原型链以及对象本身,否则我们不应该使用公共形式:if (X in Obj)…根据用例,它的速度慢2到6倍。

hasKey1 execution time: 4s 510.427785ms
hasKey2 execution time: 0s 904.374806ms
hasKey3 execution time: 0s 760.336193ms
hasKey4 execution time: 0s 935.19901ms
hasKey5 execution time: 2s 148.189608ms

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 (object . 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 (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])…因为我觉得它可读性更强。

Have fun.

玩得开心。

#14


5  

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“可以用来确定对象是否具有指定的属性作为该对象的直接属性;与操作符不同,该方法不会检查对象的原型链。

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 main want to use in, like:

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

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

I hope this helps.

我希望这可以帮助。

#15


3  

Another relatively simple way is using Object.keys. This returns an array which means you get all of the features of an array.

另一种相对简单的方法是使用Object.keys。这将返回一个数组,这意味着您将获得一个数组的所有特性。

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 JS v1.8.5

尽管我们身处一个拥有强大浏览器支持的世界。因为这个问题太老了,我想我应该加上这个:这是安全使用的JS v1.8.5。

#16


2  

With risk of massive downvoting, 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
}

#17


2  

ECMA Script 6 solution with reflect. Create wrapper like:

ECMA脚本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

#18


1  

You can also use this open source reusable component I wrote called object-hasOwnProperty.

您还可以使用我编写的名为object-hasOwnProperty的开源可重用组件。

Example:

例子:

hasOwnProperty({foo: 'bar'}, 'foo') // => true
hasOwnProperty({foo: 'bar'}, 'bar') // => false

It's quite simple:

很简单:

function hasOwnProperty(obj: {}, prop: string|number): boolean {
  return Object.prototype.hasOwnProperty.call(obj, prop);
};

#19


1  

You need to use the method object.hasOwnProperty(property). It returns true if the object has the property and false if the object doesn't.

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

#20


0  

If the key you are checking is stored in a variable, you can check it like this:

如果您正在检查的密钥存储在一个变量中,您可以这样检查它:

x = {'key': 1};
y = 'key';
x[y];

#21


0  

There is method "hasOwnProperty" exists on object, but its not recommended to call this method directly because might be sometimes the object is null or some property exist on object like: { hasOwnProperty: false }

在对象上存在方法“hasOwnProperty”,但不建议直接调用该方法,因为有时对象为null,或者对象上存在一些属性:{hasOwnProperty: false}

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

#22


0  

Do not do this object.hasOwnProperty(key)), its 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(key)),它真的很糟糕,因为这些方法可能会被问题上的对象的属性所跟踪—考虑{hasOwnProperty: false}—或者,对象可能是null对象(object. create(null))。

The best way is to do Object.prototype.hasOwnProperty.call(object, key) or:

最好的方法是做Object.prototype.hasOwnProperty。(对象、关键)或:

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