简体   繁体   English

如何在javascript中使用for循环附加对象值?

[英]How to append object value using for loop in javascript?

I loop through an array called accData and make a new array called WL and RF.我遍历一个名为 accData 的数组并创建一个名为 WL 和 RF 的新数组。 I want to make it easy to maintain, but I have a problem.我想让它易于维护,但我有一个问题。 When I want to change the WL array data to CH2 and RF array data to DIG2, I have to type the script manually.当我想将 WL 阵列数据更改为 CH2 并将 RF 阵列数据更改为 DIG2 时,我必须手动键入脚本。 This is my script这是我的脚本

const accData = [
    { st: 'serijabo', path: 'serijabo.json', wl: 'CH1', rf: 'DIG1' },
    { st: 'sukabumi', path: 'sukabumi.json', wl: 'CH2', rf: 'DIG2' },
];

for (let i = 0; i < accData.length; i++) {
  const xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function () {
  if (xhr.readyState === 4) {
    const data = JSON.parse(xhr.responseText);

    let WL = [];
    let RF = [];
    for (let i = 0; i < data.length; i++) {
      WL.push(Number(data[i].CH1)); // this line
      RF.push(Number(data[i].DIG1)); // and this line
    }
  }
 }
}

I try to use ES6 template to solve it but it is not working because the template must be place in a string.我尝试使用 ES6 模板来解决它,但它不起作用,因为模板必须放在字符串中。

WL.push(Number(data[i].`${accData[i].wl}`)); //not working
RF.push(Number(data[i].`${accData[i].rf}`)); //not working

How can I solve this?我该如何解决这个问题?

Have you tried using brackets instead of a dot?您是否尝试过使用括号而不是点? They should allow you to access properties via a string.它们应该允许您通过字符串访问属性。

WL.push(Number(data[i][`${accData[i].wl}`]));
RF.push(Number(data[i][`${accData[i].rf}`]));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM