JavaScript循环引用循环中的最后一个数字 [英] JavaScript loop referencing last number in loop

查看:108
本文介绍了JavaScript循环引用循环中的最后一个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用google可视化库,但是我不认为这是重要的。

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

我有一个名为 data.H 长度为 5

我想在此循环:

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);

问题是我的 calc 方法需要以引用 idx 。然而,idx总是5.它应该是每个循环1,2,3,4和5。

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.

这是怎么回事?如何使循环时的calc函数引用数字?

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

推荐答案

当你调用你的calc方法时,循环已经完成,所有的calc函数都会保持一个引用(相同) x idx 处于最后状态。您需要引入另一个函数/范围,以便能够冻结每个特定的 idx 。 (语法)最简单的方法是创建一个单独的函数,它将 idx 作为参数,并返回另一个函数。

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);

这篇关于JavaScript循环引用循环中的最后一个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆