The magical _javascript skill of JS and operator and OR operator

Source: Internet
Author: User

If the following question is implemented under different conditions (add_step changes), the add_level result values are different:

Copy Code code as follows:

var add_level = 0;
if (Add_step = = 5) {
Add_level = 1;
}
else if (Add_step = 10) {
Add_level = 2;
}
else if (Add_step = 12) {
Add_level = 3;
}
else if (Add_step = 15) {
Add_level = 4;
}
else {
Add_level = 0;
}

1 The above functions can also be implemented by switch:

Copy Code code as follows:

var add_level = 0;
Switch (add_step) {
Case 5:add_level = 1;
Break
Case 10:add_level = 2;
Break
Case 12:add_level = 3;
Break
Case 15:add_level = 4;
Break
Default:add_level = 0;
Break

2) Javasctipt through | | and && to achieve:

Copy Code code as follows:

var add_level = (add_step==5 && 1) | | (add_step==10 && 2) | | (add_step==12 && 3) | | (add_step==15 && 4) | | 0;

3) The 2nd way of writing can also be abbreviated as:

Copy Code code as follows:

var add_level={' 5 ': 1, ' Ten ': 2, ' ': 3, ': 4}[add_step] | | 0;

A basic formula can be drawn from the 2nd way:

Copy Code code as follows:

Add_step==5 && add_level=1

Equivalent to <==>
Copy Code code as follows:

if (add_step==5) {

Add_level = 1

}

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.