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. (因此,简单地将属性检查减少为x.key
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
是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. (您可以根据自己的情况将其更改为宽容或严格,但是至少这应该会有所帮助。)