我想用 d3 从两个一维数组创建一个表。
假设输入数组是:
array1 = ['a','b','c'];
array2 = ['d','e','f'];
我希望表格看起来像这样
ad ae af
bd be bf
cd ce cf
我应该使用嵌套选择吗?或者我应该先调用 selectAll().data()
,然后再调用 each()
? ( In real life ,每个矩阵单元格的操作不会像 'a'+'d'
那样简单,但我认为这对答案不重要。)
最佳答案
一种方法是从您的两个数组创建一个新的二维数组,使其适合标准的嵌套选择模式(参见:http://bost.ocks.org/mike/nest/):
var arr1 = ['a', 'b', 'c'],
arr2 = ['d', 'e', 'f'];
// prepare a 2D array
var data = arr1.map(function(v1) {
return arr2.map(function(v2) {
return v1 + v2;
})
});
d3.select("body").append("table")
.selectAll("tr")
.data(data)
.enter().append("tr")
.selectAll("td")
.data(Object)
.enter().append("td")
.text(String);
另一种方法是利用函数不仅传递组内元素的索引 i,还传递它所属组的索引 j 的事实:
var arr1 = ['a', 'b', 'c'],
arr2 = ['d', 'e', 'f'];
d3.select("body").append("table")
.selectAll("tr")
// arr1 corresponds to the rows
// bound data is not used in the td cells; only arr1.length is used
.data(arr1)
.enter().append("tr")
.selectAll("td")
// arr2 corresponds to the columns
.data(arr2)
.enter().append("td")
.text(function(d, i, j) { return arr1[j] + d; }); // d === arr2[i]
类似的方法使用 parentNode 而不是索引 j 从组中获取绑定(bind)数据:
var arr1 = ['a', 'b', 'c'],
arr2 = ['d', 'e', 'f'];
d3.select("body").append("table")
.selectAll("tr")
// arr1 corresponds to the rows
.data(arr1)
.enter().append("tr")
.selectAll("td")
// arr2 corresponds to the columns
.data(arr2)
.enter().append("td")
.text(function(d) { return d3.select(this.parentNode).datum() + d; });
关于javascript - d3.js:具有两个一维数组的嵌套选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14742953/