我在用数据填充 dc.js 表时遇到问题。 The documentation allows for 2 ways for doing this .
但是,我的数据已格式化,因此 3D 数据数组的元素是一个对象。在这个对象中,我存储了一些有关单元格的信息(数据类型、错误、空等)和值(当然)。
因此,我不是通过 array[row][column]
访问值,而是通过 array[row][column].csvValue
访问它。
这意味着我无法使用建议的方法来创 build 置列的函数。 (请参阅上面的链接)
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 个 jsfiddles:one where you can see my error in the console ,和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 中变量和闭包的范围及其含义的深入了解。
关于javascript - dc.js,用对象中的数据动态填充表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37176038/