d3 js:从平面数组创建嵌套数组(矩阵)

时间:2017-05-08 19:28:47

标签: javascript d3.js matrix

我有一个对象数组nodes,其中每个组件对象都有.id属性,我想创建一个方形matrix,这是一个由{{1索引的索引的嵌套数组表示逐节点交互:

[id][id]

在我得到的控制台中:

nodes.forEach(function(node, i) {
    matrix[node.id] = nodes.forEach(
        function(node1, j) {
            console.log(i,j);
            return {
                "x": j,
                "y": i,
                "z": 0
            };
    });
    console.log(i, matrix[node.id]);
});

为什么没有在表达式... 149 1 ... 149 148 149 149 149 undefined 中分配对象?为什么没有错误或警告?我该如何解决?

更新:在@pilotcam解释matrix[node.id] = ...没有返回值后,我尝试了以下内容:

forEach

仍然我的 var matrix = []; var testnodes = [{id: "aaa", a:10}, {id: "aab", a:20}, {id: "aac", a:30}, {id: "aba", a:40}] testnodes.forEach(function(node, i) { matrix[node.id] = []; // [{x: 1, y:2, z:0}, {x:2,y:3,z:0}]; testnodes.forEach( function(node1, j) { matrix[node.id][node1.id] = { x: j, y: i, z: 0 }; console.log(i,j, node.id, node1.id, matrix[node.id][node1.id]); }); console.log(i, matrix[node.id]); }); 没有填满内循环:

matrix

2 个答案:

答案 0 :(得分:2)

javascript forEach方法不返回值。你可能想做

matrix[node.id] = [];

...并在第二个forEach内操纵它。从提出的问题来看,我猜你想要这样的东西:

nodes.forEach(function(node, i) {
    matrix[node.id] = [];
    nodes.forEach(
        function(node1, j) {
            console.log(i,j);
            matrix[node.id][node1.id] = {
                "x": j,
                "y": i,
                "z": 0
            };
    });
    console.log(i, matrix[node.id]);
});

我修改了小提琴以循环遍历哈希表并显示它可能正在做你想要的。 https://jsfiddle.net/rtxbzove/

答案 1 :(得分:1)

问题是我尝试使用非整数值索引数组。正确的方法似乎使用了一个'对象' / hash table:

var matrix = {};
var testnodes = [{id: "aaa", a:10},
                 {id: "aab", a:20},
                 {id: "aac", a:30},
                 {id: "aba", a:40}]

// with simple for loops:
for (var i = 0, len = testnodes.length; i < len; i++) {
  matrix[testnodes[i].id] = {};
  for (var j = 0, len = testnodes.length; j < len; j++) {
    matrix[testnodes[i].id][testnodes[j].id] =  {
                x: j,
                y: i,
                z: 0
            };
  }
  console.log( "matrix:", matrix[testnodes[i].id] );
}
console.log( "matrix:", matrix);

或者,使用forEach循环:

testnodes.forEach(function(node, i) {
    matrix[node.id] = {};
    testnodes.forEach(
        function(node1, j) {
            console.log(i,j);
            matrix[node.id][node1.id] = {
                "x": j,
                "y": i,
                "z": 0
            };
    });
    console.log(i, matrix[node.id]);
});
相关问题