If n and guard do not exist, n==null is true, and guard is undefined in the ternary operator. If the Boolean value is converted to false, it will be equal to n, that is, the final return is undefined.
But why does it return 1?
var test=function(array,n,guard){
return (n==null || guard ? 1 : n);
};
console.log(test([]));//1
首先,你理解错了运算顺序
||(逻辑或)的运算优先级大于 三元运算符
所以 (n==null || guard ? 1 : n) 这里首先是计算 逻辑或 ,然后再去计算 三元运算符
这里就变成了
true ? 1 : n
所以输出n
另外附上一个运算优先级的图,不记得从那个书上截下来的了
||优先级高于三目 所以就是 (true || guard)? 1: n ===> true ? 1 :n