如何在循环中创建动态变量名?

我的工作是一个 Ajax 谷歌地图脚本,我需要在一个 for 循环中创建动态变量名称。

for (var i = 0; i < coords.length; ++i) {
var marker+i = "some stuff";
}

我想得到的是: marker0marker1marker2等等。 我猜 marker+i有点问题

Firebug 给了我这个: missing ; before statement

250811 次浏览

Use an array for this.

var markers = [];
for (var i = 0; i < coords.length; ++i) {
markers[i] = "some stuff";
}

I agree it is generally preferable to use an Array for this.

However, this can also be accomplished in JavaScript by simply adding properties to the current scope (the global scope, if top-level code; the function scope, if within a function) by simply using this – which always refers to the current scope.

for (var i = 0; i < coords.length; ++i) {
    this["marker"+i] = "some stuff";
}

You can later retrieve the stored values (if you are within the same scope as when they were set):

var foo = this.marker0;
console.log(foo); // "some stuff"

This slightly odd feature of JavaScript is rarely used (with good reason), but in certain situations it can be useful.

 var marker+i = "some stuff";

coudl be interpreted like this: create a variable named marker (undefined); then add to i; then try to assign a value to to the result of an expression, not possible. What firebug is saying is this: var marker; i = 'some stuff'; this is what firebug expects a comma after marker and before i; var is a statement and don't (apparently) accepts expressions. Not so good an explanation but i hope it helps.

Try this

window['marker'+i] = "some stuff";

In regards to iterative variable names, I like making dynamic variables using Template literals. Every Tom, Dick, and Harry uses the array-style, which is fine. Until you're working with arrays and dynamic variables, oh boy! Eye-bleed overload. Since Template literals have limited support right now, eval() is even another option.

v0 = "Variable Naught";
v1 = "Variable One";


for(i = 0; i < 2; i++)
{//console.log(i) equivalent is console.log(`${i}`)
dyV = eval(`v${i}`);
console.log(`v${i}`); /* => v0;   v1;  */
console.log(dyV);  /* => Variable Naught; Variable One;  */
}

When I was hacking my way through the APIs I made this little looping snippet to see behavior depending on what was done with the Template literals compared to say, Ruby. I liked Ruby's behavior more; needing to use eval() to get the value is kind of lame when you're used to getting it automatically.

_0 = "My first variable"; //Primitive
_1 = {"key_0":"value_0"}; //Object
_2 = [{"key":"value"}]    //Array of Object(s)




for (i = 0; i < 3; i++)
{
console.log(`_${i}`);           /*  var
* =>   _0  _1  _2  */


console.log(`"_${i}"`);         /*  var name in string
* => "_0"  "_1"  "_2"  */


console.log(`_${i}` + `_${i}`); /*  concat var with var
* => _0_0  _1_1  _2_2  */


console.log(eval(`_${i}`));     /*  eval(var)
* => My first variable
Object {key_0: "value_0"}
[Object]  */
}

You can use eval() method to declare dynamic variables. But better to use an Array.

for (var i = 0; i < coords.length; ++i) {
var str ="marker"+ i+" = undefined";
eval(str);
}
var marker  = [];
for ( var i = 0; i < 6; i++) {
marker[i]='Hello'+i;
}
console.log(marker);
alert(marker);

In this dynamicVar, I am creating dynamic variable "ele[i]" in which I will put value/elements of "arr" according to index. ele is blank at initial stage, so we will copy the elements of "arr" in array "ele".

function dynamicVar(){
var arr = ['a','b','c'];
var ele = [];
for (var i = 0; i < arr.length; ++i) {
ele[i] = arr[i];
]               console.log(ele[i]);
}
}
        

dynamicVar();