学习JavaScript扩展运算符的基础知识
你可以使用展开运算符... ,展开一个数组、一个对象或一个字符串。
让我们从一个数组的例子开始。鉴于
你可以用这个操作来创建一个新的数组
const b = [...a, 4, 5, 6]
你也可以用以下方法创建一个数组的副本
这也适用于对象。克隆一个对象,用:
const newObj = { ...oldObj }
使用字符串,传播操作符为字符串中的每个字符创建一个数组。
const hey = 'hey'
const arrayized = [...hey] // ['h', 'e', 'y']
这个运算符有一些相当有用的应用。最重要的是能够以非常简单的方式使用数组作为函数参数。
const f = (foo, bar) => {}
const a = [1, 2]
f(...a)
剩下的元素在处理数组解构的时候很有用。
const numbers = [1, 2, 3, 4, 5]
const [first, second, ...others] = numbers
和传播元素。
const numbers = [1, 2, 3, 4, 5]
const sum = (a, b, c, d, e) => a + b + c + d + e
const result = 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 }
这也是将两个简单的对象合并成一个的完美方式。
const object1 = {
name: 'Flavio'
}
const object2 = {
age: 35
}
const object3 = {...object1, ...object2 }