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]4やArmin Ronacherが指摘しているような、より安全だが遅い解決策は、次のようになります。
Object.prototype.hasOwnProperty = function(property) {
return typeof this[property] !== 'undefined';
};