闽公网安备 35020302035485号
let arr = [1, 2, 3, 4, 5]
let newArr = [...arr, 6, 7]
// 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"}]
// newObj = [{...}, {...}, {...}]
这是非常有用的,我已经用过几次了。主要用于更新React中的状态。let arr = ["a", "a", "a", "b", "b", "c"] let withSet = [...new Set(array)] // withSet -> ["a", "b", "c"]当唯一值很重要的时候,我个人已经用过几次了。语法很容易记住,而且Set还有更多的功能,比如.has()函数可以检查Set是否有特定的值。
let v = 4
let x = ""
let y = ""
if(v > 0){
x = "positive"
} else {
x = "negative"
}
// Do this
let x = v > 0 ? 'positive' : 'negative'
// And you can chain them! but is hard to read.
let x = v > 0 ? y.length > 0 ? 'Y < 0' : 'Y > 0' : 'V > 0'
它比使用常规的if要短得多,如果不嵌套,它的可读性也很强。我一直在使用这个,特别是在React或React Native中编程JavaScript时。let x = `string text`
let multiX = `string text line 1
string text line 2`
let exprX = `string text ${x} string text`
// -> string text string text string text
我开始越来越多地使用这些。在编写GraphQL查询语句的时候非常好用,基本上是GraphQL查询的标准。if(data && data.subdata && data.subdata.name === "cool") {
console.log("hi")
}
// 堆代码 duidaima.com
// Is the same as
if(data?.subdata?.name === "cool") {
console.log("hi")
}
我已经写了无穷无尽的if语句来检查一个值是否被设置过,这肯定会帮助解决这个问题。const x = null ?? 'string'; // x: "string" const y = 12 ?? 42; // y: 12
JavaScript作为一门语言,其扩张速度比以往任何时候都要快。至少从我开始学习它以来是这样的。而且每天我都会发现新的有趣的方法来解决问题,或者做一些更容易写、执行更快、两者兼而有之的任务,或者可能只是古怪的方法。有没有什么你已经在使用的操作符,或者有什么你从未听说过的操作符?我肯定学到了一些新的。