【发布时间】:2014-07-24 09:44:58
【问题描述】:
当我看到类似的东西时,我正在寻找一些很棒的 d3.js code examples:
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});
});
我没有立即知道如何声明 var 节点。
我的第一个猜测是把它翻译成:
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};
}
});
但是链接不再绘制了。
这两种方法有什么区别?
初始语法的意义是什么,它只是一种快捷方式还是可以提高性能?
在这种情况下是否有最佳实践可以遵循?
编辑
所以如果我尝试完全理解
link.source = nodes[link.source] || (nodes[link.source] = {name: link.source});
由于 nodes[link.source] 是一个对象,link.source 需要它的引用。这总是在发生。
-
OR 条件,我不确定能得到那部分。
我猜如果 nodes[link.source] 被定义 link.source = nodes[link.source] 返回 true 我们不需要更进一步。 p>
如果没有定义并返回 false,OR 子句强制执行...
-
nodes[link.source] 获得了一个值,因此感谢引用 link.source 指向相同的值。
我猜在这个阶段 link.source 还没有包含对 nodes[link.source] 的引用,而是它的初始值。它将包含逗号后的新引用。
我在某个地方错了吗?第 2 点对我来说似乎很奇怪。
【问题讨论】:
标签: javascript variables syntax d3.js