在 JavaScript 中构建具有唯一值的对象
Constructing an object of unique values in JavaScript
我正在查看
中的代码
http://bl.ocks.org/mbostock/2706022
和这段代码
// 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});
});
我觉得很奇怪。我理解代码应该做什么(它应该构建一个名为 "nodes" 的对象列表,其唯一值是 link.source 和 link.target),但我不理解结构.请解释上面的语句是如何工作的。
我只接受回调的第一行。第二行作为第一行。
首先是作业
link.source =
下面的表达式有两部分,
nodes[link.source] || (nodes[link.source] = {name: link.source})
^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
计算第一部分,如果结果为假,则计算第二部分。
这种方法的优点是防止对 nodes[link.source]
的新赋值
nodes[link.source] = nodes[link.source] || {name: link.source}
link.source = (nodes[link.source] = nodes[link.source] || {name: link.source})
现在是带有显式检查的版本
if (!nodes[link.source]) {
nodes[link.source] = {name: link.source};
}
link.source = nodes[link.source];
了解这个
link.source = nodes[link.source] || (nodes[link.source] = {name: link.source});
你要注意parens。
第一次迭代
作为 (nodes[link.source] = {name: link.source});
的结果,系统将输出 {name: 'Microsoft'}
此输出将被分配为 links[0].source
的值
结论,不仅是你说的构造节点object。它还更改了链接 object 内项目的结构,变为:
var links = [
{source: { name: "Microsoft"},
target
也是如此
让我知道它是否仍然难以掌握
我正在查看
中的代码http://bl.ocks.org/mbostock/2706022
和这段代码
// 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});
});
我觉得很奇怪。我理解代码应该做什么(它应该构建一个名为 "nodes" 的对象列表,其唯一值是 link.source 和 link.target),但我不理解结构.请解释上面的语句是如何工作的。
我只接受回调的第一行。第二行作为第一行。
首先是作业
link.source =
下面的表达式有两部分,
nodes[link.source] || (nodes[link.source] = {name: link.source})
^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
计算第一部分,如果结果为假,则计算第二部分。
这种方法的优点是防止对 nodes[link.source]
的新赋值
nodes[link.source] = nodes[link.source] || {name: link.source}
link.source = (nodes[link.source] = nodes[link.source] || {name: link.source})
现在是带有显式检查的版本
if (!nodes[link.source]) {
nodes[link.source] = {name: link.source};
}
link.source = nodes[link.source];
了解这个
link.source = nodes[link.source] || (nodes[link.source] = {name: link.source});
你要注意parens。
第一次迭代
作为 (nodes[link.source] = {name: link.source});
的结果,系统将输出 {name: 'Microsoft'}
此输出将被分配为 links[0].source
结论,不仅是你说的构造节点object。它还更改了链接 object 内项目的结构,变为:
var links = [
{source: { name: "Microsoft"},
target
让我知道它是否仍然难以掌握