JavaScriptでオブジェクトが特定のプロパティを持っているかどうかを確認するには?

JavaScriptでオブジェクトが特定のプロパティを持っているかどうかを確認するには?

検討してみましょう。

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

それがベストな方法なのか?

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]4Armin Ronacherが指摘しているような、より安全だが遅い解決策は、次のようになります。

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

[3]: https://stackoverflow.com/questions/135448/how-do-i-check-to-see-if-an-object-has-an-attribute-in-javascript#135568

解説 (4)

はい、そうです。) Object.prototype.hasOwnProperty.call(x, 'key')とすることもできると思いますが、これもxhasOwnProperty`というプロパティを持っていれば動作するはずです :)

しかし、これは自分自身のプロパティをテストするものです。 もし、継承されている可能性のあるプロパティを持っているかどうかをチェックしたい場合は、typeof x.foo != 'undefined'を使うことができます。

解説 (0)

OK、継承されたプロパティを必要としない場合を除いて、私は正しい答えを持っていたように見えます。

if (x.hasOwnProperty('key'))

ここでは、継承されたプロパティを含めるための他のオプションがあります。

if (x.key) // Quick and dirty, but it does the same thing as below.

if (x.key !== undefined)
解説 (3)