Come posso controllare se un oggetto ha una proprietà specifica in JavaScript?
Considera:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
È il modo migliore per farlo?
if (x.key !== undefined)
Armin Ronacher sembra avermi già battuto, ma:
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!');
}
Una soluzione più sicura, ma più lenta, come indicato da Konrad Rudolph e Armin Ronacher sarebbe:
Object.prototype.hasOwnProperty = function(property) {
return typeof this[property] !== 'undefined';
};
Sì, lo è :) Penso che puoi anche fare Object.prototype.hasOwnProperty.call(x, 'key')
che dovrebbe anche funzionare se x
ha una proprietà chiamata hasOwnProperty
:)
Ma questo verifica le proprietà proprie. Se vuoi controllare se ha una proprietà che può anche essere ereditata puoi usare typeof x.foo != 'undefined'
.
OK, sembra che io abbia avuto la risposta giusta, a meno che tu non voglia proprietà ereditate:
if (x.hasOwnProperty('key'))
Ecco alcune altre opzioni per includere le proprietà ereditate:
if (x.key) // Quick and dirty, but it does the same thing as below.
if (x.key !== undefined)