展开运算符
展开运算符,将一个数组转为用逗号分隔的参数系列 ------ 更快、更便捷的操作数组
合并数组
let a = [1,2,3]; let b = [4,5,6]; let c = [...a,...b]; // [1,2,3,4,5,6]
let colors = ["red',"green","blue"] let myColors = ["pink","orange"] let fallColors = ["white"] console.log([...fallColors,...myColors,...colors])//["white","pink","orange","red',"green","blue"]
// 可以向数组中插入新的元素 console.log(["skyblue",...fallColors,...myColors,...colors])//["skyblue","white","pink","orange","red',"green","blue"]
解构赋值
let a = [1,2,3,4,5,6] let [c,...d] = a console.log(c) // 1 console.log(d) // [2,3,4,5,6] // 展开运算符必须放在最后一位
作为参数
function addNumbers(...numbers){ return numbers.reduce((sum,number) => { return sum + number },0) } console.log(addNumbers(1,2,3,4,5)); //15
浅拷贝
//数组 var a = [1,2,4] var b = [...a] a.push(6) console.log(b) // [1,2,4] //对象 var a = {a:1} var b = {...a} a.a = 5 console.log(b.a) // 1
练习
function shoppingList(...items){ if(items.indexOf('milk') < 0){ return [milk,...items] } return items } console.log(shoppingList("meat","orange","bread")) // ["milk","meat","orange","bread"]