Today I wrote a small demo of the picture carousel, and used the judgment
First try if else , the code is as follows:
The code copy is as follows:
if(n >= count-1){
n =0;
}else{
n ++;
}
Then the code is finished, and I will prepare to optimize the code and change this paragraph to the writing method of the three-point operator.
The code copy is as follows:
n = n >= (count-1) ? n=0 : n++
The result is completely different
Then I studied the difference between the two and summarized it into one sentence: the three-point operation has a return value, but if else does not return value
The following test was done:
The code copy is as follows:
var n=1;
if(n>1){
n=0;
}else{
n++;
}
console.log(n);
Output result: 2
The three-point operation is as follows:
The code copy is as follows:
var n=1;
n = n>1?0 : n++;
console.log(n);
The output result is: 1
Insert a paragraph of other content: the difference between ++n and n++: Simply put, both n add 1 to themselves. The difference is that n++ only adds 1 after executing the following statement; while ++n first makes n+1 before executing the following statement
So what about ++n
if else statement
The code copy is as follows:
var n=1;
if(n>1){
n=0;
}else{
++n;
}
console.log(n);
Output result: 2
Three-point calculation results
The code copy is as follows:
var n=1;
n = n>1?0 : ++n;
console.log(n); The output result is: 2
You can see the difference between if else and three-point operation~~~
There is no difference between n++ and ++n in this verification, because if else is after the calculation result, it will not return n and no return value
However, for three-point operation, the n value returned by n++ is n itself, and the n value returned by ++n is the result after n+1
After reading this article, do you have a new understanding of the three-point operator and if else in js?