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:
but its displaying error: ReferenceError: answer is not defined |
||||
|
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:
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:
|
|||
|
Eval is executed in separate context. |
|||
|
You should use
|
|||||
|
EDIT: code below is not working
|
|||||||||
|