2016-05-15 137 views
1

我已經在這幾天了,我已經看到了stackoverflow和其他地方的問題,但我錯過了一些東西。d3使用節點名稱鏈接的強制圖形

比方說我們有以下的JSON:

{ 
    "nodes":[ 
    {"name":"node1"}, 
    {"name":"node2"}, 
    {"name":"node3"}, 
    {"name":"node4"} 
], 
    "links":[ 
    {"source":"node1","target":"node2"}, 
    {"source":"node1","target":"node3"}, 
    {"source":"node1","target":"node4"} 
    ] 
} 

爲什麼代碼產生以下兩件在控制檯相同的輸出,但第二個給我一個錯誤(遺漏的類型錯誤:無法讀取屬性「推「未定義)?

links = links.map(function(l) { 
    var sourceNode = nodes.filter(function(n) { return n.name === l.source; })[0]; 
    var targetNode = nodes.filter(function(n) { return n.name === l.target; })[0]; 
    return { 
    source: sourceNode, 
    target: targetNode 
    }; 
}); 

_

links.forEach(function(link) { 
    link.source = {name: link.source}; 
    link.target = {name: link.target}; 
}); 

控制檯輸出:

[{"source":{"name":"node1"},"target":{"name":"node2"}}, 
{"source":{"name":"node1"},"target":{"name":"node3"}}, 
{"source":{"name":"node1"},"target":{"name":"node4"}}] 
+0

您何時會收到錯誤? –

+0

@Lukasz,我立即得到錯誤。不知道我理解你的問題。請參閱以下兩個控制檯輸出:https://jsfiddle.net/mosley/m3xynk8q/(無錯誤)和https://jsfiddle.net/mosley/kLubuw70/(錯誤)。 – mosley

回答

0

有2個代碼段的結果之間的一個顯著差異。

第一個通過引用鏈接sourcetarget節點。他們指向nodes陣列中的對象。

第二個創建新的對象。它們與nodes中的名稱相同,但它們是內存中的不同對象。

D3強制佈局要求鏈接通過引用或通過數組中的索引指向節點。如果指定索引,則它們將按transformed to references

Note: the values of the source and target attributes may be initially specified as indexes into the nodes array; these will be replaced by references after the call to start.

+0

謝謝。你能解釋「通過引用鏈接......」,或者可能指向我可以閱讀的地方?另外,你說「他們指向節點數組中的對象」,它們是如何指向的,並且我可以看到它們確實指向了一個對象,可能是在Chrome開發人員工具中? – mosley

+0

@mosley這裏是通過引用與值傳遞數據之間的區別的一個很好的解釋:http://stackoverflow.com/a/430958/853558。你可以看到2個變量是否指向同一個對象,只需將它們與'=='或'==='進行比較即可。看看這段代碼:https://jsfiddle.net/LukaszWiktor/umnk9edm/ –

相關問題