ES6 -- 展开运算符

Posted lovekiku123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ES6 -- 展开运算符相关的知识,希望对你有一定的参考价值。

展开运算符

展开运算符,将一个数组转为用逗号分隔的参数系列 ------ 更快、更便捷的操作数组

 

合并数组

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

练习

function shoppingList(...items){
  if(items.indexOf(‘milk‘) < 0){
       return [milk,...items]    
  }
  return items
}

console.log(shoppingList("meat","orange","bread")) // ["milk","meat","orange","bread"]

 

 

以上是关于ES6 -- 展开运算符的主要内容,如果未能解决你的问题,请参考以下文章

ES6展开运算符的两个用法

ES6 -- 展开运算符

javascript兼容性:展开运算符 ... 的降级

web前端练习18----es6新语法5,展开运算符...

ES6中的展开运算符和解构对象

js之es6