ES6-rest参数和扩展运算符

来源:互联网 发布:中国万网域名申请流程 编辑:程序博客网 时间:2024/05/16 10:41

转自:http://blog.csdn.net/u010603896/article/details/76681842

三个点(...)的存在,它在ES6语法中,有两种应用形式,分别为函数中的rest参数,以及扩展运算符

REST参数

rest参数和一个变量名搭配使用,生成一个数组,用于获取函数多余的参数,说不清楚,还是代码实例演示
[javascript] view plain copy
  1. function input(...params){  
  2.     console.log(params)  
  3. }  
  4.   
  5. input(1,2,3,4)  //[1,2,3,4]  
  6.   
  7. function input2(a,b,...params){  
  8.     console.log(params)  
  9. }  
  10.   
  11. input2(1,2,3,4)  //[3,4]  
rest参数作用: 将多余的逗号分隔的参数序列转换为数组参数
注意: rest参数必须是最后一个参数,否则报错

扩展运算符

扩展运算符可以理解为rest参数的逆运算,将数组转换为逗号分隔的参数序列,应用如下
[javascript] view plain copy
  1. arr1 = [1,2,3]  
  2. arr2 = [4,5,6]  
  3. arr3 = [7,8,9]  
  4.   
  5. arr4 = [...arr1, ...arr2, ...arr3] //[1,2,3,4,5,6,7,8,9]  用于数组合并  
  6.   
  7. list = [a,b,c,d,e]  
  8.   
  9. let [a,b, ...c] = list  
  10. //a  
  11. //b  
  12. //[c,d,e]  
  13.   
  14. // 用于解耦,感觉这有点像是rest参数的应用,应为结果是数组