如何检查对象是否在JavaScript中具有属性?
考虑:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
Run Code Online (Sandbox Code Playgroud)
这是最好的方法吗?
任何人都可以启发我,hasOwnProperty和propertyIsEnumerable有什么区别:
function f(){
this.a = 1;
this.b = 2;
this.c = function(){}
}
f.prototype = {
d : 3,
e : 4,
g : function(){}
}
Run Code Online (Sandbox Code Playgroud)
创建对象的实例:
var o = new f();
Run Code Online (Sandbox Code Playgroud)
在这里,我看不出差异.在我看来,他们正在做同样的事情
o.hasOwnProperty('a'); //true
o.hasOwnProperty('b'); //true
o.hasOwnProperty('c'); //true
o.hasOwnProperty('d'); //false
o.hasOwnProperty('e'); //false
o.hasOwnProperty('g'); //false
o.propertyIsEnumerable('a'); //true
o.propertyIsEnumerable('b'); //true
o.propertyIsEnumerable('c'); //true
o.propertyIsEnumerable('d'); //false
o.propertyIsEnumerable('e'); //false
o.propertyIsEnumerable('g'); //false
Run Code Online (Sandbox Code Playgroud)
如果我错了,请找我