首页 > 编程语言 > 详细

The tilde ( ~ ) operator in JavaScript

时间:2014-10-13 15:54:50      阅读:1354      评论:0      收藏:0      [点我收藏+]

From the JavaScript Reference on MDC,

~ (Bitwise NOT)

Performs the NOT operator on each bit. NOT a yields the inverted value (a.k.a. one’s complement) of a. The truth table for the NOT operation is:

a NOT a
0 1
1 0

Example:

9 = 00000000000000000000000000001001 (base 2)
               --------------------------------
~9 = 11111111111111111111111111110110 (base 2) = -10 (base 10)

Bitwise NOTing any number x yields -(x + 1). For example, ~5 yields -6.

Now lets look at the Logical NOT(!)

! (Logical NOT)

Returns false if its single operand can be converted to true; otherwise, returns true. 

Mixing the two NOT operators together can produce some interesting results:

!~(-2) = false

!~(-1) = true

!~(0) = false

!~(1) = false

!~(2) = false

For all integer operands except -1, the net operand after applying the ~ operator for the ! operator would be truthy in nature resulting in FALSE.

-1 is special because ~(-1) gives 0 which is falsy in JavaScript. Adding the ! operator gives us the only TRUE.

When to use this special case ?

A lot of times in JavaScript String manipulation, you are required to search for a particular character in a string. For example,

1 var str = ‘posterous‘;
2  
3 if ( str.search(‘t‘) >= 0 ) {
4 // character t found
5 }
6 else{
7 // not found
8 }

We can use the operators instead of the comparison operators, like this:

1 var str = ‘posterous‘;
2  
3 if ( !~str.search(‘t‘) ) {
4 // character ‘t‘ not found branch
5 }
6 else{
7 // found branch
8 }

 

原帖地址:http://www.javascriptturnsmeon.com/the-tilde-operator-in-javascript/

The tilde ( ~ ) operator in JavaScript

原文:http://www.cnblogs.com/mliudong/p/4022219.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!