[英]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 });
}
我的理解是,如果p为null,则该父级的子级应该为空,但是为什么需要使用||。 此代码中使用的表达式
(children [p] ||(children [p] = [])
target = !p ? x : y
target = !p ? x : y
表示if not p
则target = x
。 其他target = y
(children[p] = [])
表示将空数组分配给children[p]
(children[p] || (children[p] = []))
意味着,如果children[p]
不为null,则返回该值。 否则给children[p]
分配一个空数组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];
}
|| 是逻辑或运算符或条件运算符。它根据第一个是true还是false来返回第一个或第二个操作数。 真实值表示除0 , undefined , null ,“”或false之外的任何值。
root:(children[p] || (children[p] = [])
表示如果children[p]
是真实的,则root是children[p]
否则root将是children[p]=[]
。children children[p]
将被分配一个空数组而不是一个falsey值
如果未定义children[p]
(或该值为false,undefined,null,0 ...),则使用新数组进行设置。
如果第一个操作数为falsy,则逻辑OR运算符(||)返回其第二个操作数的值,否则返回第一个操作数的值。
ei
"foo" || "bar"; // returns "foo"
false || "bar"; // returns "bar"
它是一个条件(三元)运算符?:
带有对p
的倒置校验,它是父级。
如果p
不存在,则取roots
,否则取父对象的子代或为其分配一个空数组作为默认值,并获取它。
target = !p // condition
? roots // true part
: (children[p] || (children[p] = [])); // else part
这是一种更简洁的描述方式...
if (!children[p]) {
children[p] = [];
}
有一个三元运算符来检查p
是否不是父项,然后将目标设置为子级,将p元素数组设置为新的空数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.