Differences between the three-object operator in JS and the if else operator and the example, jselse
Today I wrote a small demo of image carousel and used it to determine
First try if elseThe Code is as follows:
Copy codeThe Code is as follows:
If (n> = count-1 ){
N = 0;
} Else {
N ++;
}
After the code is written, prepare to optimize the code and change the code segment to the three-object operator.
Copy codeThe Code is as follows:
N = n> = (count-1 )? N = 0: n ++
Different Results
Then I studied the differences between the two, and concluded that the three-object operation has a return value, and if else has no return value.
The following test is performed:
Copy codeThe Code is as follows:
Var n = 1;
If (n> 1 ){
N = 0;
} Else {
N ++;
}
Console. log (n );
Output result: 2
Three-object operationAs follows:
Copy codeThe Code is as follows:
Var n = 1;
N = n> 1? 0: n ++;
Console. log (n );
Output result: 1
Insert a piece of other content: the difference between ++ n and n ++: Simply put, they all use n auto-increment 1. The difference is that n ++ adds 1 to the statement after execution, while ++ n executes the statement after n + 1.
So what about ++ n?
If else statement
Copy codeThe Code is as follows:
Var n = 1;
If (n> 1 ){
N = 0;
} Else {
++ N;
}
Console. log (n );
Output result: 2
Result
Copy codeThe Code is as follows:
Var n = 1;
N = n> 1? 0: ++ n;
Console. log (n); the output result is: 2
We can see the difference between if else and the three-object operation ~~~
N ++ and ++ n have no difference in this verification, because if else is after the calculation result, n is not returned, and no return value is returned.
However, for the three-object operation, the n value returned by n ++ is n itself, and the n value returned by ++ n is n + 1.
After reading this article, do my friends have a new understanding of the Three-object operator in js and the if else operator.