如何检查对象在JavaScript中是否具有特定属性?
考虑:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
这是最好的方法吗?
如何检查对象在JavaScript中是否具有特定属性?
考虑:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
这是最好的方法吗?
当前回答
带反射的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
其他回答
x?。如果x.key存在,key返回1,否则未定义
是的,它是:)我想你也可以做Object.protype.hasOwnProperty.call(x,'key'),如果x有一个名为hasOwnProperty:)的属性,这也应该有效
但这是对自身财产的测试。如果你想检查它是否有一个属性也可能是固有的,你可以使用typeof x.foo!='未定义”。
好吧,看来我的答案是正确的,除非你不想继承财产:
if (x.hasOwnProperty('key'))
以下是包含继承财产的其他选项:
if (x.key) // Quick and dirty, but it does the same thing as below.
if (x.key !== undefined)
JavaScript现在正在发展壮大,因为它现在有好的甚至有效的方法来检查它。
以下是检查对象是否具有特定属性的一些简单方法:
使用hasOwnProperty()
const hero = {
name: 'Batman'
};
hero.hasOwnProperty('name'); // => true
hero.hasOwnProperty('realName'); // => false
在中使用关键字/运算符
const hero = {
name: 'Batman'
};
'name' in hero; // => true
'realName' in hero; // => false
与未定义的关键字比较
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)
有关详细信息,请查看此处。
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';
};