展开运算符

170 阅读1分钟


let arr1 = [1,5,2,3]

let arr2 = [7,4,1,9]

console.log(...arr1) // 展开一个数组

console.log(...arr1, ...arr2) // 链接数组


// 在函数中使用
function sum(...numbers) {
  return numbers.reduce((preValue, currentValue) => {
    return preValue + currentValue
  })
}

console.log(sum(1,2,3,4,5,9,7,4,3)) // 38


let person = {name:'tom',age:18}

console.log(...person)
//报错,展开运算符不能直接展开一个对象

let person2 = {...person} //克隆的对象,字面量形式可复制一个


复制对象时 并修改它的属性
let person3 = {...person, name: 'jack'}
//{name: 'jack', age: 18}


合并
let person3 = {...person, name: 'jack',address: '中国'}
//{name: 'jack', age: 18, address: '中国'}