展开运算符
普通写法与展开运算符
function addNumbers(numbers) {
return numbers.reduce((sum,number)=>{
return sum+number
},0)
};
const numbers=[1,2,3,4,5];
console.log(addNumbers(numbers)) //15
function addNumbers(a,b,c,d,e) {
let numbers=[a,b,c,d,e];
return numbers.reduce((sum,number)=>{
return sum+number
},0)
};
console.log(addNumbers(1,2,3,4,5)) //15
function addNumbers(...numbers) {
return numbers.reduce((sum,number)=>{
return sum+number
},0)
};
console.log(addNumbers(1,2,3,4,5)) //15
展开运算符的应用
var defaultColor=['red','green'];
var favoriteColor=['orange','yellow'];
defaultColor=defaultColor.concat(favoriteColor);
console.log(defaultColor); //["red", "green", "orange", "yellow"]
//同理也可以直接传两个数组
console.log([...defaultColor,...favoriteColor])
//之前的数组也可以合并
var fallcolors=['fire red','fall orange'];
console.log(['blue',...fallcolors,...defaultColor,...favoriteColor])
小案例
function shopList(...items) {
if(items.indexOf('milk')<0){
return ['milk',...items]
}
};
console.log(shopList('orange','bread','eggs'))