在下面的代码中,我不确定哪个对象正在引用代码.push(node)
。如果它引用节点或父变量。
我已将 console.log()
添加到代码中,但正在更新数据和 dataMap 变量。我很困惑。
// *********** Convert flat data into a nice tree ***************
// create a name: node map
var dataMap = data.reduce(function(map, node) {
map[node.name] = node;
return map;
}, {});
// create the tree array
var treeData = [];
data.forEach(function(node) {
// add to parent
var parent = dataMap[node.parent];
if (parent) {
// create child array if it doesn't exist
(parent.children || (parent.children = []))
// add node to child array
.push(node);
} else {
// parent is null or missing
treeData.push(node);
}
});
我想理解代码。
最佳答案
// create child array if it doesn't exist
(parent.children || (parent.children = []))
// add node to child array
.push(node);
是这样的:
(parent.children || (parent.children = [])).push(node);
这与以下逻辑相同
if (!parent.children) {
parent.children = [];
}
parent.children.push(node);
关于javascript - 我不明白这个语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56469843/