# JavaScript 中的数学运算符 – JavaScript 完全手册（2018版）

### 算术运算符

#### 相加 (+)

```const three = 1 + 2
const four = three + 1
```

```const three = 1 + 2
three + 1 // 4
'three' + 1 // three1
```

#### 相减(-)

```const two = 4 - 2
```

#### 除法(/)

```const result = 20 / 5 //result === 4
const result = 20 / 7 //result === 2.857142857142857
```

```1 / 0 //Infinity
-1 / 0 //-Infinity
```

#### 取余(%)

```const result = 20 % 5 //result === 0
const result = 20 % 7 //result === 6
```

```1 % 0 //NaN
-1 % 0 //NaN
```

#### 乘法 (*)

```1 * 2 //2
-1 * 2 //-2
```

#### 求幂(**)

```1 ** 2 //1
2 ** 1 //2
2 ** 2 //4
2 ** 8 //256
8 ** 2 //64
```

### 一元运算符

#### 递增 (++)

```let x = 0
x++ //0
x //1
++x //2
```

#### 递减(–)

```let x = 0
x-- //0
x //-1
--x //-2
```

#### 一元负号(-)

```let x = 2
-x //-2
x //2
```

#### 一元正号(+)

```let x = 2
+x //2

x = '2'
+x //2

x = '2a'
+x //NaN
```

### 赋值快捷方式

`+=`：加法赋值
`-=`：除法赋值
`*=`：乘法赋值
`/=`：除法赋值
`%=`：取余赋值
`**=`：求幂赋值

```const a = 0
a += 5 //a === 5
a -= 2 //a === 3
a *= 2 //a === 6
a /= 2 //a === 3
a %= 2 //a === 1
```

### 优先级

```const a = 1 * 2 + 5 / 2 % 2
```

• `-` `+` `++` `--` 一元运算符，递增，递减
• `*` `/` `%` 乘法/除法
• `+` `-` 加法/减法
• `=` `+=` `-=` `*=` `/=` `%=` `**=` 赋值运算

```const a = 1 * 2 + 5 / 2 % 2
const a = 1 * 2 + 5 / 2 % 2
const a = 2 + 2.5 % 2
const a = 2 + 0.5
const a = 2.5
```