javascript - 在 Javascript 中调用串联变量

标签 javascript variables concatenation

有没有办法在 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/

相关文章:

javascript - 来自没有层次结构的数组的 d3 树形图

Java - 在构造函数中为多个变量分配参数

c++ - 我可以在 if 语句中枚举变量吗?

c - 如何从 C 语言的二进制文件中读取插入符号?

javascript - 将递归文件夹中的多个缩小的 javascript 文件合并到一个文件中

javascript - 有人可以解释这个 JavaScript 自动执行函数吗?

javascript - 使用 Ethers JS 估算 gas 价格

Excel VBA 宏 - 在循环中连接

javascript - Angular - 重用组件进行显示和修改会导致@input问题吗?

Javascript - 从外部访问函数闭包中的变量