Home > Web Front-end > JS Tutorial > body text

js与运算符和或运算符的妙用_javascript技巧

WBOY
Release: 2016-05-16 16:59:54
Original
1192 people have browsed it

如下题用if else实现不同条件下(add_step的变化), add_level的结果值不同:

复制代码 代码如下:

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)以上功能也可以通过switch来实现:

复制代码 代码如下:

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通过||和&&来实现:

复制代码 代码如下:

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

3)第2种写法也可以简写为:

复制代码 代码如下:

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

从第2种写法中可以得出一个基本公式:

复制代码 代码如下:

add_step==5 && add_level=1

等价于
复制代码 代码如下:

if(add_step==5){

  add_level = 1

}

Related labels:
js
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!