英文:
How to get Dynamic Variable assigned with dynamic values in loops
问题
我已经创建了一个用于获取动态变量的循环,如下所示:
var tile;
var tiles;
while (i < 16) {
this['tile' + i] = this['tiles' + i];
i++;
}
我期望它返回:
tile1=tiles1
tile2=tiles2
tile3=tiles3........
(tiles1、tiles2、tiles3.. 表示预定义变量 tiles1、tiles2、tiles3... 的值)
它确实返回了变量名称(等号左边的部分),但没有返回值(等号右边的部分)。
我是 JavaScript 新手,希望我能解释清楚问题。如何解决这个问题?
我尝试过:
this['tile' + i] = tiles + i;
this['tile' + i] = tiles[i];
this['tile' + i] = "tiles" + i;
但都没有帮助。
英文:
I have created a loop for getting dynamic variables like this:
var tile;
var tiles;
while(i<16){
this['tile'+i]=this['tiles'+i];
i++;
}
I expected it to return :
tile1=tiles1
tile2=tiles2
tile3=tiles3........
(tiles1,tiles2,tiles3.. means value of predefined varibles tiles1,2,3...)
It does return the variable name(left side of'=') but doesn't return the value (right side of'=').
I am new in JavaScript. Hope I could explain the problem.
How to solve this?
I tried
this['tile'+i]=tiles+i;
this['tile'+i]=tiles[i];
this['tile'+i]="tiles"+i;
But doesn't help.
答案1
得分: 0
如果你在声明变量时没有使用`var`关键字,那么它们将被存储在全局对象中,因此你可以执行以下操作:
```javascript
tiles1 = 1;
tiles2 = 2;
tiles3 = 3;
for (let i = 1; i <= 3; i++) {
globalThis['tile'+i] = globalThis['tiles'+i];
}
现在 console.log(tile2)
将打印出期望的 2
。
<details>
<summary>英文:</summary>
If you declare the variables without the `var` keyword then they're going to be stored inside the global this, so you can do the following:
```javascript
tiles1 = 1;
tiles2 = 2;
tiles3 = 3;
for (let i = 1; i <= 3; i++) {
globalThis['tile'+i] = globalThis['tiles'+i];
}
Now console.log(tile2)
will print 2
as desired.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论