简体   繁体   中英

Can anybody explain me this highlighted line of code?

 var roots = [], children = {};

    // find the top level nodes and hash the children based on parents
    for (var i = 0, len = arry.length; i < len; ++i) {
        var item = arry[i],
            p = item.Parent,
            target = !p ? roots : (children[p] || (children[p] = []));
         // I am not able to understand this line what it does
        // target = !p ? roots : (children[p] || (children[p] = []));
        target.push({ value: item });
    }

what I understand that if p is null then childrens for that parent should be empty but why then need to use of || expression that is used in this code

(children[p] || (children[p] = [])

Step by step

  • target = !p ? x : y target = !p ? x : y means if not p then target = x . Else target = y
  • (children[p] = []) means assign an empty array to children[p]
  • (children[p] || (children[p] = [])) means if children[p] is not null then return that. Else assign an empty array to children[p] then return it

Combining it

  • If p is null or undefined => target = roots
  • Else
    • If children[p] is NOT null then target = children[p]
    • Else children[p] = [] then target = children[p] which is an empty array

Equivalent

if (!p) {
  target = roots;
} else if (children[p]) {
  target = children[p];
} else {
  children[p] = [];
  target = children[p];
}

|| is the Logical OR operator or the Conditional operator .It returns the first or second operand depending on whether the first is truthy or falsey . A truthy value means anything other than 0 , undefined , null , "", or false .

This root:(children[p] || (children[p] = []) means that if children[p] is truthy then root is children[p] else root will be children[p]=[] . children[p] will be assigned an empty array rather than a falsey value

If children[p] is not defined (or this value is false, undefined, null, 0...), is setting with an new array.

The Logical OR operator (||) returns the value of its second operand, if the first one is falsy, otherwise the value of the first operand is returned.

ei

"foo" || "bar"; // returns "foo"
false || "bar"; // returns "bar"

Reference

It is a conditional (ternary) operator ?: with an inverted check of p , which is the parent.

If p not exists, then take roots , otherwise take children of the parent or assign an empty array to it, as default value, and take it.

target = !p                                // condition
    ? roots                                // true part
    : (children[p] || (children[p] = [])); // else part

It is a more terse way to describe...

if (!children[p]) {
  children[p] = [];
}

有一个三元运算符来检查p是否不是父项,然后将目标设置为子级,将p元素数组设置为新的空数组。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM