I was looking some great d3.js code examples when I saw something like:
var links = [
{source: "test1", target: "test2"},
{source: "test1", target: "test3"},
{source: "test2", target: "test3"},
{source: "test3", target: "test4"}
];
var nodes = {};
// Compute the distinct nodes from the links.
links.forEach(function(link) {
link.source = nodes[link.source] || (nodes[link.source] = {name: link.source});
link.target = nodes[link.target] || (nodes[link.target] = {name: link.target});
});
I didn't get immediately how the var nodes was being declared.
My first guess was to translate it into:
links.forEach(function(link) {
if(link.source != nodes[link.source]){
nodes[link.source] = {name: link.source};
}
if(link.target != nodes[link.target]){
nodes[link.target] = {name: link.target};
}
});
But the links are not drawn anymore.
What is the difference between the two methods?
What is the point of the initial syntax, is that just a shortcut or do it increase performances?
Is there a best practice to follow in such cases ?
Edit
So if I try to fully understand
link.source = nodes[link.source] || (nodes[link.source] = {name: link.source});
As nodes[link.source] is an object link.source takes its reference. This is always happening.
OR condition, I'm not sure to get that part.
I guess if nodes[link.source] is defined link.source = nodes[link.source] return true we don't need go further.
If it's not defined and return false, the OR clause force to go further...
nodes[link.source] gets a value so thanks to the reference link.source is pointing to the same value.
I guess at this stage link.source is not yet containing a reference to nodes[link.source], but its initial value. It will contain the new reference after the comma.
Am I wrong somewhere ? Point 2 seems strange to me.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…