使用Rest和Spread对对象和数组进行处理的方法

84 阅读1分钟

学习两种现代技术来处理JavaScript中的数组和对象

你可以使用扩展运算符扩展一个数组、一个对象或一个字符串。 传播操作符....

让我们从一个数组的例子开始。鉴于

你可以用下面的方法创建一个新的数组

const b = [...a, 4, 5, 6]

来创建一个新的数组,你也可以用

这也适用于对象。克隆一个对象,用:

const newObj = { ...oldObj }

使用字符串,传播操作符为字符串中的每个字符创建一个数组。

const hey = 'hey'
const arrayized = [...hey] // ['h', 'e', 'y']

这个运算符有一些相当有用的应用。最重要的是能够以一种非常简单的方式将数组作为函数参数。

const f = (arg1, arg2) => {}
const a = [1, 2]
f(...a)

(在过去,你可以用f.apply(null, a) ,但这没有那么好的可读性)

剩下的元素在处理数组解构时很有用。

const numbers = [1, 2, 3, 4, 5]
[first, second, ...others] = numbers

传播元素

const numbers = [1, 2, 3, 4, 5]
const sum = (a, b, c, d, e) => a + b + c + d + e
const sumOfNumbers = sum(...numbers)

ES2018引入了rest属性,它与此相同,但对对象而言。

休息属性。

const { first, second, ...others } = {
  first: 1,
  second: 2,
  third: 3,
  fourth: 4,
  fifth: 5
}

first // 1
second // 2
others // { third: 3, fourth: 4, fifth: 5 }

展开属性允许通过组合展开运算符后传递的对象的属性来创建一个新对象。

const items = { first, second, ...others }
items //{ first: 1, second: 2, third: 3, fourth: 4, fifth: 5 }