Comment vérifier si un objet possède une propriété spécifique en JavaScript ?
Réfléchissez :
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
Est-ce la meilleure façon de faire ?
if (x.key !== undefined)
[Armin Ronacher][1] semble m'avoir déjà [devancé][2], mais.. :
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!');
}
Une solution plus sûre, mais plus lente, [comme indiqué][3] par [Konrad Rudolph][4] et [Armin Ronacher][1], serait la suivante :
Object.prototype.hasOwnProperty = function(property) {
return typeof this[property] !== 'undefined';
};
[1] : https://stackoverflow.com/users/19990/armin-ronacher [2] : https://stackoverflow.com/questions/135448/how-do-i-check-to-see-if-an-object-has-an-attribute-in-javascript#135466 [3] : https://stackoverflow.com/questions/135448/how-do-i-check-to-see-if-an-object-has-an-attribute-in-javascript#135568 [4] : https://stackoverflow.com/users/1968/konrad-rudolph
Oui, c'est ça :) Je pense que vous pouvez aussi faire Object.prototype.hasOwnProperty.call(x, 'key')
qui devrait aussi fonctionner si x
a une propriété appelée hasOwnProperty
:)
Mais cela teste les propriétés propres. Si vous voulez vérifier s'il a une propriété qui peut aussi être héritée, vous pouvez utiliser typeof x.foo != 'undefined'
.
OK, il semble que j'avais la bonne réponse, sauf si vous ne voulez pas de propriétés héritées :
if (x.hasOwnProperty('key'))
Voici d'autres options pour inclure les propriétés héritées :
if (x.key) // Quick and dirty, but it does the same thing as below.
if (x.key !== undefined)