javascript - problem with an operator operation
怪我咯
怪我咯 2017-05-19 10:33:27
0
2
518

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
怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(2)
仅有的幸福

First of all, you misunderstood the order of operations

var test=function(array,n,guard){
    return (n==null || guard ? 1 : n); 
};
console.log(test([]));//1
The operation precedence of

|| (logical OR) is greater than that of the ternary operator

So (n==null || guard ? 1 : n) here first calculates the logical OR, and then calculates the ternary operator

Here it becomes true ? 1 : n
So output n
Attached is a picture of the priority of operations. I don’t remember which book I took it from

巴扎黑
var test=function(array,n,guard){
    console.log(n==null);//true
    return (n==null || guard ? 1 : n); 
};
console.log(test([]));//1

||The priority is higher than trinocular, so it is (true || guard)? 1: n ===> true ? 1 :n

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template