如何检查变量是否'not defined'(不仅仅是"未定义")



我想检查变量是否not defined,不包括分配给undefined的变量,没有try/catch

我知道typeof variable,但这不符合我想要的。

例如:

let a;
console.log(typeof a === typeof b); // outputs true
console.log(a); // outputs 'undefined'
console.log(b); // throws error 'b is not defined'

我想要的是能够区分未定义的变量和值为undefined的变量,而无需使用try/catch

我的用例(来自评论(是:

我想看看省略的参数和设置为未定义的参数之间的函数调用中的区别。一般来说,如果可能的话

一种可能性是使用 window.hasOwnProperty("var"(,如下所示:

不知道这是否在所有情况下都有效...

您也可以尝试使用"this"关键字而不是"window"将"hasOwnProperty"函数集中在当前作用域上。

var a;
console.log("Is a declared? "+window.hasOwnProperty("a"));
console.log("type of a: "+typeof(a));
console.log("Is b declared? "+window.hasOwnProperty("b"));
console.log("type of b: "+typeof(b));

您可以使用arguments查找省略的参数

function f(a,b) {
switch (arguments.length){
case 1:{
console.log("b omitted");
return;
}
case 0:{
console.log("a and b omitted");
return;
}
}
}
f();//a and b omitted
f(1);//b omitted

使用参数

> function f(a,b,c) { console.log(arguments) }
> f(1,2,3)
Prints:
{ '0': 1, '1': 2, '2': 3 }
> f(1,2)
Prints:
{ '0': 1, '1': 2 }
> f(1,2,undefined)
Prints:
{ '0': 1, '1': 2, '2': undefined }

最新更新