即使尚未定义变量,如何检查变量是否已被声明?

时间:2016-08-26 15:29:56

标签: javascript variables undefined undeclared-identifier

这个问题:

JavaScript check if variable exists (is defined/initialized)

不考虑已声明但未定义的变量的情况(与未声明和未定义相反)。具体来说,如果我想检查是否已声明x,请执行以下操作:

typeof x == 'undefined'

不会这样做,因为......

var x; //<- declared but undefined
// idontexist  not declared

typeof idontexist === typeof x; // evaluates to true

这有意义:如果已声明变量,它将不会成为全局变量,而如果未声明变量,则它将成为全局变量,可能导致内存泄漏。

那么如果声明了未定义的变量,我如何检查javascript?

关于这方面的含义,请考虑以下代码:

function test() {

  var x
  console.log(typeof x == typeof y); // true
  if (typeof x == 'undefined') {
     x = 3;
  } 
  if (typeof y == 'undefined') {
     y = 5; 
  }
}
test();
y; // 5
x; // Reference Error

2 个答案:

答案 0 :(得分:0)

尝试使用未声明的变量将抛出ReferenceError,因此您可以使用Observable.combineLatest([o1, o2]) .map { (responses: [Response]) -> [PopByCity] in responses.map { try? JSONDecoder().decode(PopByCity.self, from: $0.data) } .compactMap { $0 } } .subscribe(onNext: { (result: [PopByCity]) in print(result) }) .disposed(by: disposeBag) 块来确定是否已声明变量。

try catch

答案 1 :(得分:0)

我几年前已经回答了这个……,不记得在哪里了。

    "variablename" in this //> true : false

其中 this 是任何可以访问该变量名值的执行上下文。

    function exists( x ){ return x in this }
相关问题