# 神奇运算符

### ~ 按位取反

#### 字符串查找

```if (str.indexOf('a') != -1) {
...
}```

```if (~str.indexOf('a'))
...
}```

#### 取整

```var a = 2.3;
var b = Math.floor(a);```

```var a = 2.3;
var b = ~~a;```

### && 与 ||

```var result;

if status == 1) {
result = 'Andy'
}
else if(status == 2){
result = 'Tom';
}
else {
result = 'John';
}```

```var result = (status == 1 && 'Andy') ||
(status == 2 && 'Tom') || 'John';```

`var result = {'1': 'Andy', '2': 'Tom'}[status] || 'John';`

`var test = test || '1';`

```if (a === 'Andy'){
console.log ('hello ' + a);
}```

`    a === 'Andy' && console.log ('hello ' + a);`

### ^ 运算符

```var a = 1, b = 2, temp;

temp = a;
a = b;
b = temp;```

```var a = 1, b = 2;

a = a ^ b;
b = b ^ a;
a = a ^ b;```

```为直观一点方便证明让 aa = a， bb = b

// a = a ^ b
a = aa ^ b

// b = b ^ a
b = aa
= aa ^ 0
= aa ^ (bb ^ bb)
= bb ^ (aa ^ bb)
= bb ^ a

// a = a ^ b
a = bb
= bb ^ 0
= bb ^ (a ^ a)
= a ^ (bb ^ａ）
= a ^ b```

```为了简单证明我们假设arr[1] = 1, arr[2] = 2, 以此类推。
a = (arr[1] ^ arr[2] ... ^ arr[n-1]) ^ (1 ^ 2 ... ^ n - 1 ^ n)
= (arr[1] ^ 1) ^ (arr[2] ^ 2) ... ^ (arr[n-1] ^ n-1) ^ n
= 0 ^ 0 .. ^ 0 ^ n
= n```

### 其他好玩的运算符

```var a = 2.3, b = 2.3, c = 2.3;

a = a >> 0;
b = b << 0;
c = c | 0;```

```var a = '100';
a = a - '0';```

```var a = '100';
parseInt(a, 10)```

```+"100"

// 正整数
"100" | 0
"100" >> 0
"100" << 0```

```num >> 1  // 取半，偶数
num << 1  // 2倍
num & 1   // 奇偶判断```

1370 篇文章158 人订阅

0 条评论

## 相关文章

380130

39040

18730

15910

11020

19530

7920

423100

### 寻找中位数

LeetCode 295. Find Median from Data Stream 设计一个数据结构，该数据结构动态维护一组数据，且支持如下操作: 1.添...

15730

19290