JavaScript运算符宝典

Likun
2022年03月10日 18:16:44
JavaScript
阅读 682

这篇文章将详细介绍JavaScript运算符及其用法!

如果我们想导航运算符的话,可以通过cmd + fctrl + f,然后放置你需要的运算符,运算符后面跟:

举个例子:如果你想查找...运算符的话,可以这样写 ...:

P.s.人气指数非官方定义,仅图一乐。

灵巧的运算符

+:加法|一元加

人气指数:★★★★☆

如果在操作数之前使用+运算符,那么+就成为了一元加运算符。

一元加运算符位于操作数之前并计算操作数,并试图将操作数转换为数字(如果不是数字的话)。

const x = 1
const y = -1

console.log(+x)
// expected output: 1

console.log(+y)
// expected output: -1

console.log(+'')
// expected output: 0

console.log(+true)
// expected output: 1

console.log(+false)
// expected output: 0

console.log(+'hello')
// expected output: NaN

注意:如果将一元加运算符与不是数字的字符串一起使用,则返回NaN(not a number)

如果在其他上下文中使用+运算符,则用作加法运算符。

将产生除字符串之外的数字操作数的总和。

注意:它会将布尔值转换为数字,将对象转换为数字。

console.log(2 + 4// 6
console.log(2 + true// 3

当你将它与字符串一起使用时,将进行字符串连接

const name = 'code oz'
console.log('hello ' + 'my name is ' + name)

注意:你应该使用模板字符串代替连接。

-: 减法|一元否定

人气指数:★★★★☆

如果在操作数之前使用-运算符,那么-将用作一元否定运算符。

一元否定运算符位于操作数之前进行否定。

注意:它会将布尔值转换为数字,将对象转换为数字,将字符串转换为数字

const a = 5
console.log(-a) // -5
console.log(-'1'// -1

注意:如果将其与不是数字的字符串一起使用,则返回NaN(not a number)

如果在其他上下文中使用-运算符,则用作减法运算符。

减去两个操作数,产生它们的差。

console.log(5 - 3)
// expected output: 2

console.log(3.5 - 5)
// expected output: -1.5

console.log(5 - 'hello')
// expected output: NaN

console.log(5 - true)
// expected output: 4

...:扩展|rest参数

如果在函数参数中使用...运算符,它将用作rest运算符。

它允许函数拥有无限数量的参数!

let arr = [351]

Math.max(...arr) // 5 (spread turns array into a list of arguments)

如果在其他上下文中使用...运算符,它将用作扩展运算符。

如果将其用作函数中的参数:它将允许可迭代,例如函数参数中的数组表达式。

// rest parameter is handle as array in the function
const add = (...rest) => {
   return rest.reduce((total, current) => total + current)
}

// Nice your function can handle different number of parameters !
add(123)
add(12345)

你还可以使用它从数组或对象中提取值。

// We extract the first Item of the array into the variable and the others variable in an array named others
const [ firstItem, ...others ] = [ 1234 ]
firstItem // 1
others // [ 2, 3, 4 ]
const toto = { a1b2c3 }
const { a, ...others } = toto
// 1, we extract the a key from toto object
others // { b: 2, c: 3 }, we extract other key in the object thanks to rest operator 

注意:当你在做const toto = { ...anotherObject }时,它等于const toto = Object.assign({}, anotherObject)

逻辑运算符

首先我们要知道:Javascript中的所有值都是假值或真值,这意味着你可以对任何值进行布尔计算,并获得布尔值。在Javascript中,除0nullundefinedNaN、空字符串外,其他所有值都是真值。

&&:逻辑与

人气指数:★★★★★

用于检查所有值(通常值为条件)是否为真。

它将返回第一个值falsy,否则返回最终值。

const isTrue = true
const isFalse = false


const value = isFalse && isTrue // will return false 
const valueBis = isTrue && isFalse // will return false

const toto = 5 && 3 && 1 // will return 1 since all value before are true (5 & 3)

const tutu = 5 && 0 && 2 // will return 0 since it's the first falsy value

if (firstCondition && secondCondition) { console.log('hello') } // console log will be shown only if both condition are true!

&&=:逻辑与赋值

人气指数:★☆☆☆☆

仅当传递的值为真时才赋值。

let toto = 0
let tutu = 2

toto &&= 5 // toto value will be NOT changed since toto is falsy (0)
tutu &&= 3 // tutu value will be replaced by 3 since tutu is trusly (2)

// toto &&= 5 It's a shortcut of 👇

let toto = 0 

toto = toto && 5

||:逻辑或

人气指数:★★★★☆

用于检查一组值中的一个值(通常值是条件)是否为真。

它将返回第一个值truthy,否则返回最终值。

const isTrue = true
const isFalse = false

const value = isFalse || isTrue // will return true 
const valueBis = isTrue || isFalse // will return true

const toto = 5 || 3 || 1 // will return 5 since it's the first truthy value

const tutu = 0 || 2 || 5 // will return 2 since it's the first truthy value

if (firstCondition || secondCondition) { console.log('hello') } // console log will be shown if one condition matches!

||=:逻辑或赋值

人气指数:★☆☆☆☆

仅当传递的值为假时才赋值。

let toto = 0
let tutu = 2

toto ||= 5 // toto value will be replaced by 5 since toto is falsy (0)
tutu ||= 3 // tutu value will NOT changed since tutu is not a falsy value (2)

// toto ||= 5 It's a shortcut of 👇

let toto = 0 

toto = toto || 5

??: 逻辑空合并

人气:★★★☆☆

当其左侧操作数为nullundefined (空值)时,返回其右侧操作数。

const toto = 0 ?? 55 // 0 since 0 is not equal to nullish value.
const tutu = null ?? 'hello' // 'hello' since the right-hand side is equal to `null`
const tata = undefined ?? 55 // '55 since the right-hand side is equal to `undefined`
const titi = null ?? undefined // undefined since the right-hand side is equal to `null`

注意:??运算符与||不同,因此当你需要根据其他值来赋值时,应该选择正确的运算符!

const toto = 0 || 55 // 55 since 0 is a falsy value
const titi = 0 ?? 55 // 0 since 0 is different of nullish value

const tutu = undefined || 55 // 55 since undefined is a falsy value
const tata = undefined ?? 55 // 55 since undefined is equal to nullish value

??=: 逻辑空赋值

人气指数:★☆☆☆☆

仅当传递的值等于nullundefined (nullish)时才赋值。

let toto = null
toto ??= 55 // toto is equal to 55 since it's a nullish value (null)

let tutu = 90
tutu ??= 23 // toto is equal to 90 since it's not a nullish value (90)
// toto ??= 5 It's a shortcut of 👇

let toto = null

toto = toto ?? 5 // Equal to 5 since toto is equal to null

!: 逻辑非

人气指数:★★★★★

将真值交换为假值,将假值交换为真值。

还会将任何值转换为布尔值。所以所有真值都变成假值,反之亦然。

提示:我经常使用双逻辑运算符来将任何值转换为布尔值。它相当于使用布尔值(任何值哦)

console.log(!true// false
console.log(!true// true
console.log(!0// false
console.log(!1// true

console.log(!{}) // false
console.log(![]) // false
console.log(!undefined// true

// My tips 👇
console.log(!!{}) // true, equal to Boolean({})
console.log(!![]) // true, equal to Boolean([])

if (!!value) { ... } // I use a lot in order to check if a value is defined or undefined! (Be careful, if the value is equal to `0` it will be false!)

特殊运算符

?.: 可选链

人气指数:★★★★☆

它允许访问对象上的属性,而无需检查链中的每个引用是否有效。

是不是不明白?看看下面的例子你就知道了:

const toto = { a: { b5 } }
toto.a // { b: 5 }
toto.a.b // 5
toto.a.b.c // undefined
toto.a.b.c.d // Uncaught TypeError: Cannot read properties of undefined

实际上,当你尝试访问未定义属性上的属性时,Javascript引擎将触发错误!

所以为了安全起见,我们需要像这样做:

const toto = { a: { b5 } }

if (toto.a && toto.a.b && toto.a.b.c && toto.a.b.c.d) {
    console.log(toto.a.b.c.d) // It's safe to use it since we check before if the property exist!
}

但是这样不太方便,是吧?

所以可选链来拯救我们了。

如上所示,你可以尝试访问一个属性,而无需检查之前是否存在所有属性!你只需要在属性上使用此运算符,如果该属性不存在,则返回undefined

const toto = { a: { b5 } }
toto?.a?.b // 5
toto?.a?.b?.c?.d // undefined

?: 三元运算符

人气指数:★★★★☆

这是JavaScript中唯一需要两个伪操作数(?:)的运算符。它根据条件是假还是真来评估条件。等价于if (...) & else (...)

console.log(true ? 55 : 10// 55
console.log(0 ? 13 : 34// 34

const toto = 2 > 1
console.log(toto ? 'ok' : 'not ok')

//  It's a shortcut of 👇

if (toto) {
    console.log('ok')
else {
    console.log('not ok')
}

比较运算符

==:相等

人气指数:★☆☆☆☆

检查两个操作数是否相等,并返回布尔结果。与===(严格相等运算符)不同,它尝试转换(进行隐式强制)并比较不同类型的操作数。

下面是如何完成隐式强制的示例!

// 1) Not the same type so implicit coercion will be made
'24' == 24

// 2) Convert string into number so 
Number('24') == 24

// 3) We got an number so we can check value
24 == 24 // true !

通常,你应该使用===(严格相等),并避免使用此运算符!

===:严格相等

人气指数:★★★★★

检查两个操作数是否相等,并返回布尔结果。与==(相等运算符)不同,严格相等运算符始终认为不同类型的操作数是不同的。

console.log(1 === 1)
// expected output: true

console.log('hello' === 'hello')
// expected output: true

console.log('1' ===  1)
// expected output: false

console.log(0 === false)
// expected output: false

你应该始终使用此运算符而不是==(相等运算符)!

!=: 不等于

人气指数:★☆☆☆☆

检查两个操作数是否不相等,并返回布尔结果。与!==(严格不等于运算符)不同,它尝试转换和比较不同类型的操作数。

console.log(1 != 1)
// expected output: false

console.log('hello' != 'hello')
// expected output: false

console.log('1' !=  1)
// expected output: false

console.log(0 != false)
// expected output: false

通常,你应该使用!==(严格不等于)并避免使用此运算符!

!==: 严格不等于

人气:★★★★★

检查两个操作数是否不相等,并返回布尔结果。与!=(不等于运算符)不同,严格不等于运算符始终认为不同类型的操作数是不同的。

console.log(1 !== 1)
// expected output: false

console.log('hello' !== 'hello')
// expected output: false

console.log('1' !==  1)
// expected output: true

console.log(0 !== false)
// expected output: true

你应该始终使用此运算符而不是!=(不等于)!

>:大于

人气指数:★★★★☆

如果左操作数大于右操作数,则返回true,否则返回false。

console.log(5 > 3)
// expected output: true

console.log(3 > 3)
// expected output: false

console.log('ab' > 'aa')
// expected output: true

>=:大于或等于

人气指数:★★★★☆

如果左操作数大于或等于右操作数,则返回true,否则返回false。

console.log(5 >= 3)
// expected output: true

console.log(3 >= 3)
// expected output: true

console.log('ab' >= 'aa')
// expected output: true

<:小于

人气指数:★★★★☆

如果左操作数小于右操作数,则返回true,否则返回false。

console.log(5 < 3)
// expected output: false

console.log(3 < 3)
// expected output: false

console.log('aa' < 'ab')
// expected output: true

<=:小于或等于

人气:★★★★☆

如果左操作数小于或等于右操作数,则返回true,否则返回false。

console.log(5 <= 3)
// expected output: false

console.log(3 <= 3)
// expected output: true

// Compare bigint to number (note: bigint is not supported in all browsers)
console.log(3n <= 5)
// expected output: true

console.log('aa' <= 'ab')
// expected output: true

算术运算符

+=:加法赋值

人气指数:★★★☆☆

右操作数的值加到变量,并将结果赋值给变量。

let a = 5
let b = 3

b += a // b will be equal to 8, since we are adding 5 to b variable!

-=:减法赋值

人气指数:★★★☆☆

右操作数的值减去变量,并将结果赋值给变量。

let a = 5
let b = 3

b -= a // b will be equal to 2, since we are subtracting 5 to b variable

*:乘法

人气指数:★★★☆☆

产生操作数的乘积。

let a = 5
let b = 3

let c = a * b // 15

*=:乘法赋值

人气:★★★☆☆

右操作数的值乘以变量,并将结果赋给变量。

let a = 5
let b = 3

b *= a // 15

/:除法

人气指数:★★★☆☆

产生操作数的商,其中左操作数是被除数,右操作数是除数。

let a = 10
let b = 2

let c = a / b // 2

console.log(1 / 0// Infinity

/=:除法赋值

人气:★★★☆☆

右操作数的值除以变量,并将结果赋给变量。

let a = 10
let b = 2

b /= a // 2

**:求幂

人气指数:★★★☆☆

返回第一个操作数作为底数,第二个操作数作为指数的求幂结果。等同于Math.pow,不同在于**也接受BigInts作为操作数。

let a = 10
let b = 2

let c = a ** b // 100, it equals to 10^2 or Math.pow(10, 2)

**=:求幂赋值

人气:★★★☆☆

将变量的值提升到右操作数的幂。

let a = 10
let b = 2

b **= a // 1024, it equals to 2^10 or Math.pow(2, 10)
a **= b // 100, it equals to 10^2 or Math.pow(10, 2)

%:余数(取模)

人气指数:★☆☆☆☆

返回一个操作数除以第二个操作数时剩余的余数。总是带被除数的符号。

let a = 10
let b = 3

let c = a % b // 1

%=: 余数赋值

人气:★☆☆☆☆

变量除以右操作数的值,并将余数赋值给变量。

let a = 10
let b = 3

a %= b // 1 it's equal to a % b

++:增量

人气指数:★★★☆☆

增加(加一)操作数并返回一个值。

你可以通过两种方式使用:

作为预增量:在操作前增加值

let toto = 55

console.log(toto) // 55
console.log(++toto) // 56
console.log(toto) // 56

作为后增量:在操作后增加值

let toto = 55

console.log(toto) // 55
console.log(toto++) // 55
console.log(toto) // 56

--:减量

人气指数:★★★☆☆

减少(减一)操作数并返回一个值。

你可以通过两种方式使用:

作为预减量:在操作前递减值

let toto = 55

console.log(toto) // 55
console.log(--toto) // 54
console.log(toto) // 54

作为后减量:在操作后递减值

let toto = 55

console.log(toto) // 55
console.log(toto--) // 55
console.log(toto) // 54

位运算符

&:按位与

人气指数:★☆☆☆☆

在两个操作数的对应位均为1的每个位位置返回1。

注意:不要混淆&&&运算符。&&是逻辑运算符AND

const a = 5        // 00000000000000000000000000000101
const b = 3        // 00000000000000000000000000000011

console.log(a & b) // 00000000000000000000000000000001

小提示:如果你需要检查一个数是否为偶数,可以使用numberVar & 1,如果结果等于0,那就是偶数!

&=:按位与赋值

人气指数:★☆☆☆☆

使用两个操作数的二进制表示,对它们进行按位与运算并将结果分配给变量。

let a = 5      // 00000000000000000000000000000101
a &= 3         // 00000000000000000000000000000011

~:按位取反

人气:★☆☆☆☆

取反操作数的位。与其他按位运算符一样,将操作数转换为32位有符号整数

const a = 5     // 00000000000000000000000000000101
const b = -3    // 11111111111111111111111111111101

console.log(~a) // 11111111111111111111111111111010
// expected output: -6

console.log(~b) // 00000000000000000000000000000010
// expected output: 2

|: 按位或

人气:★☆☆☆☆

在其中一个操作数或两个操作数的相应位为1时,在每个位位置返回一个1。

const a = 5        // 00000000000000000000000000000101
const b = 3        // 00000000000000000000000000000011

console.log(a | b) // 00000000000000000000000000000111
// expected output: 7

|=:按位或赋值

人气指数:★☆☆☆☆

使用两个操作数的二进制表示,对它们进行按位或运算并将结果分配给变量。

let a = 5      // 00000000000000000000000000000101
a |= 3         // 00000000000000000000000000000011

console.log(a) // 00000000000000000000000000000111
// expected output: 7

^:按位异或

人气指数:★☆☆☆☆

当其中任一操作数但不是两个操作数的相应位是1时,在每个位位置返回一个1。

const a = 5        // 00000000000000000000000000000101
const b = 3        // 00000000000000000000000000000011

console.log(a ^ b) // 00000000000000000000000000000110

^=:按位异或赋值

人气指数:★☆☆☆☆

使用两个操作数的二进制表示,对它们进行按位异或运算并将结果分配给变量。

let a = 5      // 00000000000000000000000000000101
a ^= 3         // 00000000000000000000000000000011

console.log(a) // 00000000000000000000000000000110
// expected output: 6

<<: 按位左移

人气指数:★☆☆☆☆

将第一个操作数向左移动指定的位数。左移的多余位将被丢弃。零位从右侧移入。

const a = 5         // 00000000000000000000000000000101
const b = 2         // 00000000000000000000000000000010

console.log(a << b) // 00000000000000000000000000010100
// expected output: 20

<<=:按位左移赋值

人气指数:★☆☆☆☆

向左移动指定数量的位并将结果赋值给变量。

let a = 5 // 00000000000000000000000000000101

a <<= 2   // 00000000000000000000000000010100

console.log(a)
// expected output: 20

>>:右移

人气指数:★☆☆☆☆

将第一个操作数向右移动指定的位数。右移的多余位将被丢弃。最左侧位的副本从左边移入。

由于新的最左侧位与前一个最左侧位具有相同的值,因此符号位(最左侧位)不会改变。所以又叫做符号传播。

const a = 5          //  00000000000000000000000000000101
const b = 2          //  00000000000000000000000000000010
const c = -5         // -00000000000000000000000000000101

console.log(a >> b)  //  00000000000000000000000000000001
// expected output: 1

console.log(c >> b)  // -00000000000000000000000000000010
// expected output: -2

>>=:按位右移赋值

人气指数:★☆☆☆☆

向右移动指定数量的位并将结果赋值给变量。

let a = 5      //  00000000000000000000000000000101

a >>= 2        //  00000000000000000000000000000001
console.log(a)
// expected output: 1

let b = -5     // -00000000000000000000000000000101

b >>= 2        // -00000000000000000000000000000010
console.log(b)
// expected output: -2

>>>:无符号右移

人气指数:★☆☆☆☆

将第一个操作数向右移动指定的位数。右移的多余位将被丢弃。

零位从左侧移入。

符号位变为0,因此结果始终为非负。与其他按位运算符不同,0填充的右移返回一个无符号的32位整数。

const a = 5          //  00000000000000000000000000000101
const b = 2          //  00000000000000000000000000000010
const c = -5         // -00000000000000000000000000000101

console.log(a >>> b) //  00000000000000000000000000000001
// expected output: 1

console.log(c >>> b) //  00111111111111111111111111111110
// expected output: 1073741822

>>>=:无符号右移赋值

人气指数:★☆☆☆☆

向右移动指定数量的位并将结果赋值给变量。

let a = 5 //  00000000000000000000000000000101

a >>>= 2  //  00000000000000000000000000000001
console.log(a)
// expected output: 1

let b = -5 // -00000000000000000000000000000101

b >>>= 2   //  00111111111111111111111111111110
console.log(b)
// expected output: 1073741822

希望这篇教程能对大家有所帮助。祝编码快乐!


JavaScript
0
1
生成海报
发表评论
请登录后发布评论
评论列表 (1)

Likun (管理员)

2年前
浙江省 杭州市 滨江区
Mac OS 10.15.7
回复
学习了
今日访问量81
昨日访问量158
本月访问量3234
总访问量61379
本网站由 提供CDN加速/云存储服务
Copyright © 2024 Likun 版权所有 豫ICP备19029335号-1 浙公网安备 33010602012440号 Powered by Node.js