"&","&&";"|","||"的用法(整理)

参考:http://developers-heaven.net/forum/index.php?topic=56.0

   http://www.javaeye.com/topic/462449

从下面那篇文章中的(i & 1) == 0说起,当i的对位与的值为1时,比如1,3,5,i&1返回是1,否则返回是0(比如2,4,6)。

再看以下需求:

成长速度为15显示4个箭头;

成长速度为12显示3个箭头;

成长速度为10显示2个箭头;

成长速度为5显示1个箭头;

成长速度为0显示0个箭头。

用&&和||替代if及swith...case的写法:

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

更简洁的写法:

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

请你一定要记住:在js逻辑运算中,0、""、null、false、undefined、NaN都会判为false,其他都为true。这个一定要记住,不然应用||和&&就会出现问题。

这里顺便提下:看到很多代码if(!!attr),为什么不直接写if(attr);
其实这是一种更严谨的写法:
请测试 typeof 5和typeof !!5的区别。!!的作用是把一个其他类型的变量转成的bool类型。

另:

1 - In the conditional statements:

just like the & and && operator, the double Operator || is a "short-circuit" operator
For example:
if(condition1 || condition 2 || condition 3)

If condition1 is true, condition 2 and 3 will NOT be checked.

if(condition1 | condition 2 | condition 3)

This will check conditions 2 and 3, even if 1 is already true.

2- There is a Second use of the | and & operator though: Bitwise Operations.

 | is the bitwise OR operator. Its used to operate on two numbers. You look at each bit of each number individually and, if one of the bits is 1 in at least one of the numbers, then the resulting bit will be 1 also. Here are a few examples:

A = 01010101
B = 10101010
A | B = 11111111
A & B = 00000000
A = 00000001
B = 00010000
A | B = 00010001
A & B = 00000000
A = 10001011
B = 00101100
A | B = 10101111
A & B = 00001000

与运算(&)的规则:1与1等于1,1与0等于0。
比如:10010001(二进制)&11110000等于10010000(二进制)。

或运算(|)的规则是:1或1等1,1或0等于1,
0或0等于0。比如10010001(二进制)| 11110000(二进制)等于11110001(二进制)
posted @ 2011-03-23 17:40  peter cheng  阅读(11705)  评论(0编辑  收藏  举报