【问题标题】:dc.js, fill table with data from object dynamicallydc.js,用对象中的数据动态填充表
【发布时间】:2016-05-12 02:02:54
【问题描述】:

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

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

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

这意味着我不能使用建议的方式来创建设置列的函数。 (见上面的链接)

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 consoleone working example using just a 3D-array without an object inside each cell

【问题讨论】:

标签: javascript d3.js dc.js


【解决方案1】:

正如 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 中变量和闭包的作用域及其含义的见解。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多