JavaScript loop referencing last number in loop

2019-04-15 12:04发布

问题:

Working with the google visualization library, however I dont think that matters here.

I have a variable called data.H with has a length of 5

I want to loop over that here:

var cols = new Array();
        for (var x = 1; x < data.H.length + 1; x++) {
          var idx = x - 1;
          console.log(idx);
          cols.push({
              type: 'number',
              label: data.getColumnLabel(idx),
              calc: function (dt, row) {
                  console.log("row: ", row, "Idx: ",idx);
                  var val = dt.getValue(0, idx); // this is always 5
                  for (var i = 1, total = 0, cols = dt.getNumberOfColumns(); i < cols; i++) {
                      total += dt.getValue(row, i);
                  }
                  var percent = val / total;
                  return {v: percent, f: (percent * 100).toFixed(2) + '%'}; // return value and value
              }
          });
        };
        view.setColumns(cols);

The problem is that my calc method needs to reference idx. However idx is always 5. It should be 1,2,3,4 and 5 on each loop.

What is going on here? How do I make the calc function reference the number at the time of the loop?

回答1:

By the time you call your calc methods, the loop will be already finished, and all calc functions will be keeping a reference to (the same) x and idx at their last state. You need to introduce another function/scope, to be able to "freeze" each particular idx. The (syntactically) simplest way is to create a separate function that takes idx as an argument, and returns another function.

function createCalcFunction(idx) {
    return function (dt, row) {
        /* make a local copy */
        var localIdx = parseInt(idx, 10);
        console.log("row: ", row, "Idx: ",localIdx);

        var val = dt.getValue(0, localIdx);

        for (var i = 1, total = 0, cols = dt.getNumberOfColumns(); i < cols; i++) {
          total += dt.getValue(row, i);
        }
        var percent = val / total;
        return {v: percent, f: (percent * 100).toFixed(2) + '%'}; // return value and value
    }
}

var cols = [];
for (var x = 1; x < data.H.length + 1; x++) {
    var idx = x - 1;
    console.log(idx);
    cols.push({
        type: 'number',
        label: data.getColumnLabel(idx),
        calc: createCalcFunction(idx);
    });
};
view.setColumns(cols);