js与或优先级 替换 if else

偶然见到下面的写法,半天没猜透,Google一番,记录下来。

var id=15;

var outID = id==5 && 1 || id==10 && 2 || id==15 && 3 || id==20 && 4 || 0;//outID=3

其实上面这个等价于

if(id=5){
outID
=1;
}
else if(id=10){
outID
=2;
}
else if(id=15){
outID
=3;
}
else if(id=20){
outID
=4;
}
else{
outID
=0;
}

多数程序语言中||和&&都遵循“短路”原理,如&&中第一个表达式为假就不会去处理第二个表达式,而||正好相反。
js也遵循上述原则。但是比较有意思的是它们返回的值。

console.log(true&&1);// 1
console.log(false&&1);// false
console.log(true||1);// true
console.log(false||1);//1

另外:在js逻辑运算中,0、''、null、false、undefined、NaN都会判为false,其他都为true;

另一种更为强大的写法.
var outID={'5':1,'10':2,'15':3,'20':4}[id] || 0; //outID=3

posted on 2011-08-18 18:13  hhfu001  阅读(516)  评论(0)    收藏  举报

导航