如何检查对象在JavaScript中是否具有特定属性?
考虑:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
这是最好的方法吗?
如何检查对象在JavaScript中是否具有特定属性?
考虑:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
这是最好的方法吗?
当前回答
让我们在这里消除一些困惑。首先,让我们通过假设hasOwnProperty已经存在来简化;目前使用的绝大多数浏览器都是如此。
如果传递给它的属性名已添加到对象中,hasOwnProperty返回true。它完全独立于分配给它的实际值,而实际值可能完全未定义。
因此:
var o = {}
o.x = undefined
var a = o.hasOwnProperty('x') // a is true
var b = o.x === undefined // b is also true
然而:
var o = {}
var a = o.hasOwnProperty('x') // a is now false
var b = o.x === undefined // b is still true
问题是当原型链中的对象具有值为undefined的属性时会发生什么?hasOwnProperty将为false,也将为false!==未定义。然而,对于。。中仍将在枚举中列出它。
最重要的是,没有跨浏览器的方法(因为Internet Explorer不公开__prototype__)来确定特定标识符是否未附加到对象或其原型链中的任何内容。
其他回答
if(x.hasOwnProperty("key")){
// …
}
因为
if(x.key){
// …
}
如果x.key错误(例如,x.key==“”),则失败。
您可以使用此选项(但请阅读以下警告):
变量x={“密钥”:1};如果(x中的“键”){console.log('has');}
但要注意:即使x是一个空对象,x中的“constructor”也会返回true。最好使用Object.hasOwn(x,'key')。
好吧,看来我的答案是正确的,除非你不想继承财产:
if (x.hasOwnProperty('key'))
以下是包含继承财产的其他选项:
if (x.key) // Quick and dirty, but it does the same thing as below.
if (x.key !== undefined)
迭代对象自身财产的更好方法:
如果要在不使用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);
}
带反射的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