tableaux - Vérifier si une clé existe dans un objet JavaScript

Mots clés : javascriptarraysobjectjavascript

meilleur 5 Réponses tableaux - Vérifier si une clé existe dans un objet JavaScript

vote vote

91

var obj = { key: undefined }; console.log(obj["key"] !== undefined); // false, but the key exists!
var obj = { key: undefined }; console.log("key" in obj); // true, regardless of the actual value
var obj = { not_key: undefined }; console.log(!("key" in obj)); // true if "key" doesn't exist in object console.log(!"key" in obj);   // Do not do this! It is equivalent to "false in obj"
var obj = { key: undefined }; console.log(obj.hasOwnProperty("key")); // true
vote vote

84

 var bizzareObj = {valid_key:  undefined}; 
var result = "Impression" in array; 
12,931,832 ±0.21% ops/sec      92% slower  
var result = array.hasOwnProperty("Impression") 
16,021,758 ±0.45% ops/sec     91% slower 
var result = array["Impression"] === undefined 
168,270,439 ±0.13 ops/sec     0.02% slower  
var result = array.Impression  === undefined; 
168,303,172 ±0.20%     fastest 
var a = {1: null};  console.log(a[1] === undefined); // output: false. I know the value at position 1 of a[] is absent and this was by design, i.e.:  the value is defined.  console.log(a[0] === undefined); // output: true. I cannot say anything about a[0] value. In this case, the key 0 was not in a[]. 
vote vote

77

var aa = {hello: "world"};  alert( aa["hello"] );      // popup box with "world"  alert( aa["goodbye"] );    // popup box with "undefined"
// note the three equal signs so that null won't be equal to undefined if( aa["goodbye"] === undefined ) {     // do something } 
// this works even if you have {"goodbye": undefined} if( "goodbye" in aa ) {     // do something } 
vote vote

67

"key" in obj 
vote vote

58

("true" in ["true", "false"]) // -> false (Because the keys of the above Array are actually 0 and 1) 

Questions similaires