如何在 JavaScript 中检查未定义的变量

答案

if (yourvar === null) // Does not execute if yourvar is `undefined`
if (typeof yourvar !== 'undefined') // Any scope
if (yourvar !== undefined)
if ('membername' in object) // With inheritance
if (object.hasOwnProperty('membername')) // Without inheritance
if (yourvar)
if (typeof someVar === 'undefined') {
  // Your variable is undefined
}
typeof x === "undefined"
x == null
if (!x) {
   //Undefined
}
if (typeof x !== "undefined") {
    //Do something since x is defined.
}
function doSomething(variable)
{
    var undef;

    if(variable === undef)
    {
         alert('Hey moron, define this bad boy.');
    }
}

您还可以使用三元条件运算符:

var a = "hallo world";
var a = !a ? document.write("i dont know 'a'") : document.write("a = " + a);

//var a = "hallo world";
var a = !a ? document.write("i dont know 'a'") : document.write("a = " + a);

if (window.x) {
    alert('x exists and is truthy');
} else {
    alert('x does not exist, or exists and is falsy');
}
var variable;
if (variable === undefined){
    console.log('Variable is undefined');
} else {
    console.log('Variable is defined');
}
var x; // declaration
x = 2; // assignment
if(typeof x  !==  "undefined") {
    alert(x);
}
void 0
// undefined

if (variable === void 0) {
    // variable is undefined
}