dc.js,用对象中的数据动态填充 table

dc.js, fill table with data from object dynamically

我在使用数据填充 dc.js table 时遇到问题。 The documentation allows for 2 ways for doing this.

但是,我的数据经过格式化,因此 3D 数据数组的元素是一个对象。在这个对象中,我存储了一些关于单元格的信息(数据类型、错误、空等)和值(当然)。

所以我没有通过 array[row][column] 访问值,而是通过 array[row][column].csvValue 访问它。

这意味着我无法使用建议的方法来创建设置列的函数。 (见上面的link)

chart.columns([function(d) { return d.date; }, ... ]);

所以我希望我的数组看起来像(如果我有 3 列):

chart.columns([function(d) { return d[0].cellValue; }, 
               function(d) { return d[1].cellValue; },
               function(d) { return d[2].cellValue; } ]);

为了动态创建这个数组,我遍历每一列并向数组添加一个函数。 这种方法行不通,因为我在内部函数中有一个变量 i,它在这个循环之外是未定义的。但是如果我的函数中没有行 i 的变量,我想不出一种构建这个数组的方法。

for (var i = 0; i < cellInfo[0].length; i++) {
    columnArray[i] = function(d) {return d[i].cellValue; /* d[i] produces the error */};
}

我创建了 2 个 jsfiddle:one where you can see my error in the console, and one working example using just a 3D-array without an object inside each cell.

正如 andiwand 所指出的,需要一个闭包来解决我的问题。我还编辑了 jsfiddle(通过在函数周围添加括号)。

添加闭包的关键行是:

for (var i = 0; i < data.length; i++) {
    columnArray[i] = (function(i){ return function(d) {return d[i].cellValue;}; })(i);
}

有关此主题的有趣读物是 closure documentation from developers.mozilla.org。它提供了对 JS 中变量和闭包的范围界定及其含义的见解。