如何在循环中获取分配动态值的动态变量

huangapple go评论60阅读模式
英文:

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&lt;16){
this[&#39;tile&#39;+i]=this[&#39;tiles&#39;+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[&#39;tile&#39;+i]=tiles+i;
 this[&#39;tile&#39;+i]=tiles[i];
 this[&#39;tile&#39;+i]=&quot;tiles&quot;+i;

But doesn't help.

答案1

得分: 0

如果你在声明变量时没有使用`var`关键字那么它们将被存储在全局对象中因此你可以执行以下操作

```javascript
tiles1 = 1;
tiles2 = 2;
tiles3 = 3;
for (let i = 1; i &lt;= 3; i++) {
    globalThis[&#39;tile&#39;+i] = globalThis[&#39;tiles&#39;+i];
}

现在 console.log(tile2) 将打印出期望的 2


<details>
<summary>英文:</summary>

If you declare the variables without the `var` keyword then they&#39;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 &lt;= 3; i++) {
    globalThis[&#39;tile&#39;+i] = globalThis[&#39;tiles&#39;+i];
}

Now console.log(tile2) will print 2 as desired.

huangapple
  • 本文由 发表于 2023年6月15日 15:46:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76480209.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定