问题
How do I create a dynamic variable in Javascript?
For example, I have:
var myAwesomeText = "Hello World!"
But now I want the varible MyAesomeText to have a random number attached to it every time the page is refreshed. So it would instead look like something like this:
var myAwesomeText12345 = "Hello World!"
And most importantly, how do I call that that new random variable back once the random number has been assigned to it? (i.e: alert(???);)
I've tried something like this, but I'm going wrong with this somewhere.
var myRnd = Math.floor(Math.random()*100000);
var myVar = "MyAwesomeText" + myRnd;
str = myVar + ' = ' + '"Hello World!"';
eval(str);
alert(str);
回答1:
You can access the variable via the window
object:
var myRnd = Math.floor(Math.random()*100000);
var myVar = "MyAwesomeText" + myRnd;
window[myVar] = "Hello World!";
alert(window[myVar]);
Don't use eval
for this: it is slower and completely unnecessary for this problem. Also it can have unexpected side-effects if your MyAwesomeText
has characters in it that have special meaning in JavaScript code, such as brackets, semi-colon, colon, comma, braces, ... etc.
Note that the notation object['prop']
gives the same result as object.prop
. Since global variables are created in the window
object, you can access any variable via the window.myvariable
notation.
Combining these two facts, you can access global variables that have a dynamic name with window[dynamicVariableName]
.
回答2:
eval is the way to go
var num = 10;
var string = "var a"+num +"= 'hi'"
string
// "var a10= 'hi'"
eval(string)
a10
// 'hi'
回答3:
You miss one eval on the alert
var myRnd = Math.floor(Math.random()*100000);
var myVar = "MyAwesomeText" + myRnd;
str = myVar + ' = ' + '"Hello World!"';
eval(str);
alert(eval(myVar));
来源:https://stackoverflow.com/questions/37309448/javascript-dynamic-variable-random-number-added