javascript - Détecter une propriété d'objet indéfinie

Mots clés : javascriptobjectundefinedobject-propertyjavascript

meilleur 5 Réponses javascript - Détecter une propriété d'objet indéfinie

vote vote

95

if(o.myProperty === undefined) {   alert("myProperty value is the special value `undefined`"); } 
if(!o.hasOwnProperty('myProperty')) {   alert("myProperty does not exist"); } 
if(typeof myVariable === 'undefined') {   alert('myVariable is either the special value `undefined`, or it has not been declared'); } 
if(myVariable === void 0) {   alert("myVariable is the special value `undefined`"); } 
vote vote

90

if (typeof myVar === "undefined") 
var undefined = false;  // Shockingly, this is completely legal! if (myVar === undefined) {     alert("You have been misled. Run away!"); } 
vote vote

80

var snapshot = …;  if (typeof snaposhot === 'undefined') {     //         ^     // misspelled¹ – this will never run, but it won’t throw an error! } 
var foo = …;  if (typeof foo === 'undefned') {     //                   ^     // misspelled – this will never run, but it won’t throw an error! } 
var foo = …;  if (foo === undefined) {     ⋮ } 
if (typeof foo.bar === 'undefined') {     ⋮ } 
if (foo.bar === undefined) {     ⋮ } 
vote vote

70

if (something == undefined) 
var person = {     name: "John",     age: 28,     sex: "male" };  alert(person.name); // "John" alert(person.fakeVariable); // undefined 
vote vote

53

var o = { a: undefined } 
typeof o.a == 'undefined' // true typeof o.b == 'undefined' // true o.a === undefined // true o.b === undefined // true 'a' in o // true 'b' in o // false 
obj.prop === undefined // IMHO, see "final fight" below 
'prop' in obj 

Questions similaires