5个JavaScript小技巧

1、展开运算符
允许对数组或字符串等迭代符进行扩展

let arr = [1, 2, 3, 4, 5]
let newArr = [...arr, 6,7]
let obj = [{name: "GME", desc: "To the moon"}, {name: "John", desc: "Doe"}]
let newObj = [...obj, {name: "Jane", desc: "Doe"}]

2、Set Object
Set对象是JavaScript中的一种新的对象类型,可以用来创建没有重复的数组。当你想拥有一个唯一值的列表时,这很有用。

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

3、三元运算符

let v = 4; 
let y= [123]; 
let x = v > 0 ? y.length > 0 ? 'Y < 0' : 'Y > 0' : 'V > 0';
console.log(x) // Y < 0
let v = 4; 
let y= ''; 
let x = v > 0 ? y.length > 0 ? 'Y < 0' : 'Y > 0' : 'V > 0';
console.log(x) // Y > 0

4、 ?操作符
?操作符或可选的链式运算符是一个很有用的运算符,用于检查一个值是否已经被设置,当它被设置后再继续。

const data = {subdata:{name:'cool'}};
if(data && data.subdata && data.subdata.name === "cool") {
  console.log("hi")
}
// Is the same as
if(data?.subdata?.name === "cool") {
  console.log("hi")
}

5、??操作符
??操作符是一个检查一条语句左值是否为空的操作符,如果为真,它将返回右边的值。

const x = null ?? 'string';
// x: "string"
const y = 12 ?? 42;
// y: 12

你可能感兴趣的:(5个JavaScript小技巧)