根据计数结果创建动态变量名

Jon*_*now 2 javascript variables jquery

我正在尝试将字符串和数字组合到动态生成的变量中。目前是这样试的:

const ElementCount = 2;

for (i = 1, i <= ElementCount, i++) {
    let SampleVariable[i] = "test";
}
Run Code Online (Sandbox Code Playgroud)

ElementCount 稍后将是动态的。

上面函数的结果应该是这样的:

SampleVariable1 = "test"
SampleVariable2 = "test"
Run Code Online (Sandbox Code Playgroud)

我的代码似乎是错误的 - 我需要在这里更改什么?解决方案也可以是原生 JS 或 jQuery。

非常感谢!

kz-*_*-xu 5

解决方案是使用eval,但它是讨厌的代码,避免使用'eval',只需使用arrayobject

1、eval解决方法:

const ElementCount = 2;

for (let i = 1; i <= ElementCount; i++) {
    eval("let SampleVariable[" + i + "] = 'test'");
}
Run Code Online (Sandbox Code Playgroud)

2、array解决方法:

const ElementCount = 2;
let Variables = []
for (let i = 1; i <= ElementCount; i++) {
    Variables["SampleVariable" + i] = "test";
}
Run Code Online (Sandbox Code Playgroud)

3、object解决方法:

const ElementCount = 2;
let Variables = {}
for (let i = 1; i <= ElementCount; i++) {
    Variables["SampleVariable" + i] = "test";
}
Run Code Online (Sandbox Code Playgroud)