本文共 1910 字,大约阅读时间需要 6 分钟。
spread运算符
You can expand an array, an object or a string using the spread operator ...
.
您可以使用传播运算符...
扩展数组,对象或字符串。
Let’s start with an array example. Given
让我们从一个数组示例开始。 给定
const a = [1, 2, 3]
you can create a new array using
您可以使用创建新数组
const b = [...a, 4, 5, 6]
You can also create a copy of an array using
您还可以使用创建一个数组的副本
const c = [...a]
This works for objects as well. Clone an object with:
这也适用于对象。 克隆对象:
const newObj = { ...oldObj }
Using strings, the spread operator creates an array with each char in the string:
使用字符串,spread运算符使用字符串中的每个字符创建一个数组:
const hey = 'hey'const arrayized = [...hey] // ['h', 'e', 'y']
This operator has some pretty useful applications. The most important one is the ability to use an array as function argument in a very simple way:
该运算符具有一些非常有用的应用程序。 最重要的一个功能是以一种非常简单的方式将数组用作函数参数的能力:
const f = (foo, bar) => {}const a = [1, 2]f(...a)
The rest element is useful when working with array destructuring:
在处理数组解构时, rest元素非常有用:
const numbers = [1, 2, 3, 4, 5]const [first, second, ...others] = numbers
and spread elements:
和传播元素 :
const numbers = [1, 2, 3, 4, 5]const sum = (a, b, c, d, e) => a + b + c + d + econst result = sum(...numbers)
ES2018 introduces rest properties, which are the same but for objects.
ES2018引入了其余属性,但对象相同。
Rest properties:
休息性质 :
const { first, second, ...others } = { first: 1, second: 2, third: 3, fourth: 4, fifth: 5}first // 1second // 2others // { third: 3, fourth: 4, fifth: 5 }
Spread properties allow to create a new object by combining the properties of the object passed after the spread operator:
传播属性允许通过组合在传播操作符之后传递的对象的属性来创建新对象:
const items = { first, second, ...others }items //{ first: 1, second: 2, third: 3, fourth: 4, fifth: 5 }
It is also the perfect way to merge two simple objects into one:
这也是将两个简单对象合并为一个的理想方法:
const object1 = { name: 'Flavio'}const object2 = { age: 35}const object3 = {...object1, ...object2 }
翻译自:
spread运算符
转载地址:http://dtqgb.baihongyu.com/