JavaScript-扩展运算符
扩展运算符能将数组转换为逗号分割的参数序列
const arr = ['1','2','3']
function get(){
console.log(arguments) // 展开数组
}
get(...arr)
1
2
3
4
5
6
2
3
4
5
6
数组合并
const arr1 = ['1','2','3']
const arr2 = ['4','5','6']
const total = [...arr1,...arr2]
1
2
3
4
2
3
4
数组克隆
const arr1 = ['1','2','3']
const arr2 = [...arr1]
1
2
2
将伪数组转为真正的数组
const divs = document.querySelectorAll('div')
const divArr = [...divs]
1
2
2
在函数中使用
// 接收不固定的参数
function sum(...numbers){
return numbers.reduce((preValue,currentValue)=>{
return preValue + currentValue
})
}
console.log(sum(1,2,3,4));
1
2
3
4
5
6
7
2
3
4
5
6
7
构造字面量对象时使用展开语法
let person = {name:'tom',age:18}
let person2 = {...person} // 深拷贝
//console.log(...person); //报错,展开运算符不能展开对象
person.name = 'jerry'
1
2
3
4
2
3
4
合并并修改
let person = {name:'tom',age:18}
let person3 = {...person,name:'jack',address:'地球'}
console.log(person3)
1
2
3
2
3
上次更新: 2024/08/14, 04:14:33