我有對象nodes
,其中每個組件對象具有.id
屬性的陣列的嵌套陣列(矩陣),並且我想創建正方形matrix
其是由[id][id]
索引的嵌套數組代表節點到節點的相互作用:D3 JS:創建從一個扁平陣列
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
爲什麼對象是不是在表達matrix[node.id] = ...
分配?爲什麼沒有錯誤或警告?我該如何解決它?
UPD:以下@pilotcam解釋是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
是沒有得到填充在內循環:
...
3 1 aba aab Object { x: 1, y: 3, z: 0 }
3 2 aba aac Object { x: 2, y: 3, z: 0 }
3 3 aba aba Object { x: 3, y: 3, z: 0 }
3 Array [ ]
似乎爲我工作。查看https://jsfiddle.net/6gxvyncf/ – pilotcam
後[添加螢火蟲插件](http://stackoverflow.com/questions/17382200/print-var-in-jsfiddle),我得到相同的輸出與上面的小提琴;(你在小提琴中得到了什麼輸出?你可以將它發佈在你的答案中嗎? –
矩陣在任何一個循環內似乎都沒有被修改 –