有没有办法在 JavaScript 循环的每次迭代中包含变量?例如,如果我将此代码放入循环中
if (e1) {item_text += '{id:"' + id[1] + '",lvl:' + e1lvl + '},<wbr>'}
if (e2) {item_text += '{id:"' + id[2] + '",lvl:' + e2lvl + '},<wbr>'} // etc
然后做类似的事情
for (n = 0; n < id.length; n++) {
if (e/*concat var e w/var n?*/) {
item_text += '{id:"' + id[1] + '",lvl:' + e/*concat var e w/var n?*/lvl + '},<wbr>'
}
}
有没有办法在每次迭代时更改变量名称中的数字(e1
-> e2
等),或者我只需要长期保留它将所有内容都写在自己的行上?
最佳答案
尽管强烈不推荐,但可能使用eval
来得出变量名称:
const e1lvl1 = 'foo';
const e2lvl1 = 'bar';
for (let i = 1; i < 3; i++) {
console.log(eval('e' + i + 'lvl1'));
}
但最好修复脚本的架构,这样就没有必要了:将每个 e#lvl
放入数组中,然后访问适当的索引每次迭代时的数组:
const elvl = [
'foo',
'bar'
];
let item_text = '';
for (let i = 0; i < elvl.length; i++) {
item_text += 'lvl: ' + elvl[i] + '\n';
}
console.log(item_text);
关于javascript - 在 Javascript 中调用串联变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51575425/