JavaScipt 小技巧

JavaScipt 小技巧

1. 展开运算符

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

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中的状态。

2. Set Object

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

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

当唯一值很重要的时候,我个人已经用过几次了。语法很容易记住,而且Set还有更多的功能,比如.has()函数可以检查Set是否有特定的值。

3. 三元运算符

三元运算符是一个速记的条件运算符。它对于根据其他条件设置值很有用。例如,在React中,如果所有的数据都已加载,那么就可以根据条件来设置View。

let v = 4let x = ""let y = ""if(v > 0){x = "positive"} else {x = "negative"}// Do thislet 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时。

4. 模板字符串

模板字符串是JavaScript中字符串的一种形式。它们用反引号(`)代替常规引号。它们使用${expression}接受表达式,并且它们可以跨越多行。

let x = string textlet multiX = string text line 1 
              string text line 2let exprX = string text ${x} string text// -> string text string text string text

我开始越来越多地使用这些。在编写GraphQL查询语句的时候非常好用,基本上是GraphQL查询的标准。

5. ?操作符

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

if(data && data.subdata && data.subdata.name === "cool") {console.log("hi")}// Is the same asif(data?.subdata?.name === "cool") {console.log("hi")}

我已经写了无穷无尽的if语句来检查一个值是否被设置过,这肯定会帮助解决这个问题。

6. ??操作符

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

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

当空值检查或返回一个尚未加载的字符串时,这可能非常有用。

你可能感兴趣的:(web前端,js)