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?
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
andidx
at their last state. You need to introduce another function/scope, to be able to "freeze" each particularidx
. The (syntactically) simplest way is to create a separate function that takesidx
as an argument, and returns another function.