简体   繁体   中英

How should I refactor an eval loop in Javascript?

I inherited a codebase that has this style of code and no tests:

  var series1 = [];
  var series2 = [];
  var series3 = [];
  var series4 = [];
  var series5 = [];
  var series6 = [];
  var series7 = [];
  var series8 = [];
  for (var y = 1; y <= seriesData.length; y++) {
      // columns are series
      eval("series" + y).push({
        label: "series" + y,
        lineColor: colorArr[seriesData[y - 1].colorIndex],
        x: sampleTime,
        y: rows[x][seriesData[y - 1].index]
      });
  } 

The main problem is that we're going to start accommodating more than 8 sets of data. Personally, I don't really appreciate this style of code, and I've read the eval function can be harmful in JS. Is there a better way to refactor this?

What I've tried:

  let multiarr = []
  for (var y = 1; y <= seriesData.length; y++) {
    // columns are series
    let arr = [];
    arr.push({
      label: "series" + y,
      lineColor: colorArr[seriesData[y - 1].colorIndex],
      x: sampleTime,
      y: rows[x][seriesData[y - 1].index]
    });

  }
  multiarr.push(arr);

You could collect all arrays in a single array and push by taking an index.

var series1 = [],
    series2 = [],
    series3 = [],
    series4 = [],
    series5 = [],
    series6 = [],
    series7 = [],
    series8 = [],
    data = [series1, series2, series3, series4, series5, series6, series7, series8];

for (var y = 0; y < seriesData.length; y++) {
    data[y].push({
        label: "series" + (y + 1),
        lineColor: colorArr[seriesData[y].colorIndex],
        x: sampleTime,
        y: rows[x][seriesData[y].index]
    });
}

The initial code seems a bit strange. You have a block of series arrays, but each one only gets pushed with a single item. Couldn't it simply be reduced to:

const result = seriesData.map((item, i) => ({
  label: `series${i + i}`,
  lineColor: colorArr[item.colorIndex],
  x: sampleTime,
  y: rows[x][item.index]
}))

If for some reason, you do actually need each of the items to themselves be an array, just do:

const multiarr = seriesData.map((item, i) => [{
  label: `series${i + i}`,
  lineColor: colorArr[item.colorIndex],
  x: sampleTime,
  y: rows[x][item.index]
}])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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