admin管理员组

文章数量:1312728

How to defined a variable in Javascript, if its not defined. I tried:

var str = "answer";
if(eval(str) == undefined)
   eval("var " + str + " = {}");
alert(answer);

but its displaying error: ReferenceError: answer is not defined

How to defined a variable in Javascript, if its not defined. I tried:

var str = "answer";
if(eval(str) == undefined)
   eval("var " + str + " = {}");
alert(answer);

but its displaying error: ReferenceError: answer is not defined

Share Improve this question edited Mar 29, 2015 at 17:25 Artjom B. 62k26 gold badges135 silver badges229 bronze badges asked Mar 29, 2012 at 8:19 RizRiz 10.2k8 gold badges42 silver badges54 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 7

If you have to do it from a name that's in a javascript variable (that isn't known ahead of time), then you can do it like this:

var str = "answer";
if (typeof window[str] == "undefined") {
    window[str] = {};
}

This uses the fact that all global variables are properties of the window object (in a browser).


If you know the name of the variable ahead of time, then you can simply do this:

var answer = answer || {};

if (typeof answer == "undefined") var answer = {};

Eval is executed in separate context.

You should use typeof with === operator and 'undefined' (to be sure that nobody overwrote undefined variable) to check if variable is undefined and when it is then assign value to it:

if (typeof answer === 'undefined') {
    var answer = 'Foo bar';
}
if(someUndefinedVariable === undefined){
    var someUndefinedVariable = 'whatever you want' 
}
alert(someUndefinedVariable) //obviously not undefined anymore

EDIT: code below is not working

or if you do not know the variable name at time of writing the code

var propertyName = 'answer'; //could be generated during runtime
if(window[propertyName] === undefined){
    var window[propertyName] = 'whatever you want';
}
alert(window[propertyName]);

本文标签: define a variable if its undefined using JavascriptStack Overflow