我不明白这种语法

时间:2019-06-06 01:17:57

标签: javascript

在下面的代码中,我不确定哪个对象在引用代码.push(node)。如果是指节点或父变量。

我已将console.log()放在代码中,但是正在更新data和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);
    }
});

我想了解代码。

1 个答案:

答案 0 :(得分:7)

// 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);