根据计数结果创建动态变量名称 [英] Create dynamic variable names based on count result
本文介绍了根据计数结果创建动态变量名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将字符串和数字组合到动态生成的变量中. 目前以这种方式尝试过:
I am trying to combine a string and number to a dynamiclly generated variable. Currently tried it this way:
const ElementCount = 2;
for (i = 1, i <= ElementCount, i++) {
let SampleVariable[i] = "test";
}
ElementCount稍后将是动态的.
ElementCount will later on be dynamic.
以上功能的结果应如下所示:
The result of the above function should look like this:
SampleVariable1 = "test"
SampleVariable2 = "test"
我的代码似乎是错误的-我必须在这里更改什么? 解决方案也可以是本地JS或jQuery.
My code seems to be wrong - what do I have to change here? Solution can be native JS or jQuery as well.
非常感谢!
推荐答案
解决方案是使用eval
,但这是讨厌的代码,请避免使用'eval',而只需使用array
或object
.
solution is to use eval
, but It's nasty code, Avoid using 'eval', just use an array
or object
.
1,eval
解决方案:
const ElementCount = 2;
for (let i = 1; i <= ElementCount; i++) {
eval("let SampleVariable[" + i + "] = 'test'");
}
2,array
解决方案:
const ElementCount = 2;
let Variables = []
for (let i = 1; i <= ElementCount; i++) {
Variables["SampleVariable" + i] = "test";
}
3,object
解决方案:
const ElementCount = 2;
let Variables = {}
for (let i = 1; i <= ElementCount; i++) {
Variables["SampleVariable" + i] = "test";
}
这篇关于根据计数结果创建动态变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文