如何检查变量是否为“未定义”(不是简单地为“未定义”)

时间:2018-07-02 15:24:19

标签: javascript

我想检查变量是否为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的变量之间的区别。

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

  

我想看看在函数调用中省略和设置为未定义的参数之间的区别。而且通常,如果可能的话

3 个答案:

答案 0 :(得分:1)

一种可能性是使用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));

答案 1 :(得分:0)

您可以使用layout.addView(view)

查找省略的参数
arguments

答案 2 :(得分:-1)

使用参数

> 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 }