The difference analysis and example _javascript technique of three-mesh operator and if else in JS

Source: Internet
Author: User

Today wrote a picture of the little demo, used to judge

first try the If Else, the code is as follows:

Copy Code code as follows:

if (n >= count-1) {
n = 0;
}else{
n + +;
}

Then the code is finished, ready to optimize the code, the paragraph changed to the three-mesh operator of the wording

Copy Code code as follows:

n = n >= (count-1)? n=0:n++

The results are completely different.

Then we studied the difference between the two, summed up as a sentence: three mesh operation has a return value, if else no return value

The following tests were done:

Copy Code code as follows:

var n=1;
if (n>1) {
n=0;
}else{
n++;
}
Console.log (n);

Output Result: 2


Three mesh operations are as follows:

Copy Code code as follows:

var n=1;
n = n>1?0:n++;
Console.log (n);
The output is: 1

Insert something else: the difference between ++n and n++: Simply put, it's all n from 1. The difference is that n++ is executed after the statement is added to 1, and ++n do the n+1 before executing the following statement

So what about ++n?

If Else statement

Copy Code code as follows:

var n=1;
if (n>1) {
n=0;
}else{
++n;
}
Console.log (n);
Output Result: 2

The results of the three-mesh operation

Copy Code code as follows:

var n=1;
n = n>1?0: ++n;
Console.log (n); The output is: 2


can see if else and three mesh operation of the difference between ~ ~ ~

n++ and ++n in this validation, there is no difference, because if else is the result of the calculation, does not return n, no return value

But for the three-mesh operation, the n++ returns the n value of n itself, ++n returns the value of n as the result of n+1

Read this article, the small partners are not the JS in the three-mesh operator and if else has a new understanding of it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.