Comment puis-je vérifier pour undefined dans JavaScript

Mots clés : javascriptundefinedjavascript

meilleur 5 Réponses Comment puis-je vérifier pour undefined dans JavaScript

vote vote

95

// global scope var theFu; // theFu has been declared, but its value is undefined typeof theFu; // "undefined" 
"theFu" in window; // true "theFoo" in window; // false 
if (typeof myVar !== 'undefined') 
window.undefined = "foo"; "foo" == undefined // true 
 false 0 "" NaN null undefined 
// abc was never declared. if (abc) {     // ReferenceError: abc is not defined }  
// or it's a property that can throw an error Object.defineProperty(window, "myVariable", {      get: function() { throw new Error("W00t?"); },      set: undefined  }); if (myVariable) {     // Error: W00t? } 
vote vote

80

myVar === undefined 
window.setTimeout = function () {     alert("Got you now!"); }; 
if (window.someVar === undefined) {     doSomething(); } 
if (typeof myVar !== "undefined") {     doSomething(); } 
var iAmUndefined; 
if ("myVar" in window) {     doSomething(); } 
vote vote

79

myVariable === undefined 
if (typeof someUndeclaredVariable == "undefined") {     // Works }  if (someUndeclaredVariable === undefined) {      // Throws an error } 
vote vote

62

if (typeof something != "undefined") {     // ... } 
vote vote

55

if (abc === void 0) {     // Undefined } 
var abc; start = +new Date(); for (var i = 0; i < 10000000; i++) {     if (TEST) {         void 1;     } } end = +new Date(); end - start; 
Test: | abc === undefined      abc === void 0      typeof abc == 'undefined' ------+--------------------------------------------------------------------- x10M  |     13678 ms               9854 ms                 9888 ms   x1  |    1367.8 ns              985.4 ns                988.8 ns 

Questions similaires