spread运算符_JavaScript Spread运算符

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 + e
const 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 // 1
second // 2
others // { 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 }

翻译自: https://flaviocopes.com/javascript-spread-operator/

spread运算符

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值