谁能向我解释这一突出显示的代码行?

时间:2019-02-20 09:47:30

标签: javascript

ORDER BY

据我了解,如果p为null,则该父级的子级应该为空,但是为什么需要使用||。此代码中使用的表达式

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

6 个答案:

答案 0 :(得分:3)

一步一步

  • target = !p ? x : y 的意思是if not p,然后是target = x。其他target = y
  • (children[p] = []) 表示将空数组分配给children[p]
  • (children[p] || (children[p] = [])) 表示如果children[p]不为null,则返回该值。否则为children[p]分配一个空数组,然后将其返回

将其组合

  • 如果p is null or undefined => target = roots
  • 其他
    • 如果children[p] is NOT null,则 target = children[p]
    • 否则 children[p] = [] ,然后是 target = children[p] ,这是一个空数组

等效

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

答案 1 :(得分:2)

|| 是逻辑 OR 运算符或 Conditional运算符。它根据第一个操作数是否为< strong> 真实 。真实值表示除 0 未定义,“”或 false 以外的任何值。

root:(children[p] || (children[p] = [])意味着如果children[p] truthy ,则root是children[p],否则root将是children[p]=[]children[p]将被分配一个空数组,而不是一个 falsey

答案 2 :(得分:1)

如果未定义children[p](或者该值为false,undefined,null,0 ...),则使用新数组进行设置。

  

逻辑“或”运算符(||)返回其第二个操作数的值,如果第一个操作数为假,则返回第一个操作数的值。

e.i。

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

Reference

答案 3 :(得分:1)

这是一个conditional (ternary) operator ?:,其倒置支票为items.add("New item"); adapter.notifyDataSetChanged(); ,是父级。

如果p不存在,则采用p,否则采用父级的子级或为其分配一个空数组作为默认值,并采用它。

roots

答案 4 :(得分:1)

这是一种更简洁的描述方式...

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

答案 5 :(得分:0)

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

相关问题