JavaScript check if variable exists (is defined/initialized)

前端 未结 29 1146
孤城傲影
孤城傲影 2020-11-22 00:59

Which method of checking if a variable has been initialized is better/correct? (Assuming the variable could hold anything (string, int, object, function, etc.))



        
29条回答
  •  伪装坚强ぢ
    2020-11-22 01:20

    To check if a variable has been declared/set I did this dirty trick.

    I haven't found a way to extract the code to a function, even with eval.

    "use strict";
    
    // var someVar;
    
    var declared;
    try {
      someVar;
      declared = true;
    } catch(e) {
      declared = false;
    }
    
    if (declared) {
      console.log("someVar is declared; now has the value: " + someVar);
    } else {
      console.log("someVar is not declared");
    }
    

提交回复
热议问题