码迷,mamicode.com
首页 > 其他好文 > 详细

ES6 -- 展开运算符

时间:2020-02-25 18:00:28      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:UNC   sum   操作   indexof   展开   numbers   func   dex   size   

展开运算符

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

 

合并数组

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 -- 展开运算符

标签:UNC   sum   操作   indexof   展开   numbers   func   dex   size   

原文地址:https://www.cnblogs.com/lovekiku123/p/12362693.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!