JavaScript常用小技巧

88 阅读1分钟

1. 展开运算符

展开运算符允许对数组或字符串等迭代符进行扩展。这对于添加新的值是非常有用的。

let arr = [1, 2, 3, 4, 5]
let newArr = [...arr, 6, 7]
console.log(newArr)  //输出[1, 2, 3, 4, 5, 6, 7]


let obj = [{name: "GME", desc: "To the moon"}, {name: "John", desc: "Doe"}]
let newObj = [...obj, {name: "Jane", desc: "Doe"}]
console.log(newObj)  //[{…}, {…}, {…}]

2.数组去重

方法一:

let arr = ["a", "a", "a", "b", "b", "c"]
let withSet = [...new Set(arr)]
console.log(withSet)  //["a", "b", "c"]

3. ?操作符 和 ??操作符

1.一个问号 ?

使用?可以极大的精简某些代码,比如说下面的例子:

data && data.subdata && data.subdata.name === 'Tom'

等价于

data?.subdata?.name === 'Tom'

let data = {
    subdata:{
        name:"Tom"
    }
}
if(data && data.subdata && data.subdata.name === 'Tom'){
    console.log(110)
}
//输出110
//上面的if可以简写为
if(data?.subdata?.name === 'Tom'){
    console.log(110)
}
//输出110

2.两个问号 ?? ??操作符是一个检查一条语句左值是否为空的操作符,如果为真,它将返回右边的值。 当空值检查或返回一个尚未加载的字符串时,这可能非常有用。

const x = null ?? 'hello'
console.log(x) //输出:string

const y = 1 ?? 2
console.log(y) //输出:1