扩展运算符(spread)是三个点(...), 可以说我在 JavaScript 中最喜欢的运算符了。
我主要在以下 3 种情况下使用:
1、拷贝数组
const arr = [1, 2, 3, 4]
const newArr = [...arr]
console.log(newArr) // [1, 2, 3, 4]
2、合并数组
const numArr = [1, 2, 3, 4]
const alphaArr = ['a', 'b', 'c']
const newArr = [...numArr, ...alphaArr]
console.log(newArr) // [1, 2, 3, 4, 'a', 'b', 'c']
3、展开对象
const rectangle = { width: 10, height: 10 }
const cube = { ...rectangle, length: 7 }
console.log(cube) // {width: 10, height: 10, length: 7}
以上就是本文的全部内容,感谢大家支持JScript之家——编程学习者社区!
|