https://www.cnblogs.com/guanghe/p/11157201.html I
wrote so many JS, only to find that the grammar of JS belongs to the C language family, and it is quite different from some parts of the general C language programming language. Among them && and || are one example.
The && and || in the
C language family have a feature, no matter what you write the expression in a mess, it will return a Boolean value.
1,&&
When both conditions are true, the result is true;
If one is false, the result is false;
When the first condition is false, the following conditions are no longer judged;
Note: When the value participates in the logical AND operation, the result is true, then the second true value will be returned; if the result is false, the first false value will be returned.
2,||
As long as one condition is true, the result is true;
When both conditions are false, the result is false;
When a condition is true, the following conditions are no longer judged;
Note: When the value participates in the logical OR operation, the result is true, and the first value that is true will be returned; if the result is false, the second value that is false will be returned;
The && and ||
in JS 1, the && and || in JS, when appearing in conditional judgment statements, such as if, will follow the C language rules.
2. The && and || in JS, when they were in assignment statements, such as variable assignment, return result, etc., will follow the following rules:
Expression a && Expression b: Calculate the result of expression a (or function),
if it is True, execute expression b (or function) and return the result of b;
if it is False, return the result of a;
Expression a || expression b: calculate the result of expression a (or function),
if it is Fasle, execute expression b (or function), and return the result of b;
if it is True, return the result of a ;
Example 1:
1 let b, c, d;
2 b = true || 0;//b=true;
3 c = false || 0;//c=0;
4 d = 1 || 0;//d=1;
例2:
1 //Turn the members with Boolean value of false in the array to 0
2 Array.from([1,, 2,, 3], (n) => n || 0)
3 // [1, 0, 2, 0, 3]