ES6----拓展運算符 三個點【...】

【...】拓展運算符是什麼?node

es6中引入擴展運算符(...),它用於把一個數組轉化爲用逗號分隔的參數序列,它經常使用在不定參數個數時的函數調用,數組合並等情形。由於typeScript是es6的超集,因此typeScript也支持擴展運算符。es6

【...】用在什麼地方?數組

一、可變參數個數的函數調用app

function push(array, ...items) {  
  array.push(...items);  
}  

function add(...vals){
  let sum=0;
  for(let i=0;i<vals.length;i++){
    sum+=vals[i];
  }
  return sum;
}

let arr = [1,2,3,4,5,6];
let sum = add(...arr);
console.log(sum);  //21

二、更便捷的數組合並函數

let arr1 = [1,2];
let arr2 = [5,6];
let newArr = [20];
//es5 舊寫法
newArr = newArr.concat(arr1).concat(arr2); //[20,1,2,5,6]
console.log(newArr);
//es6 使用擴展運算符
newArr = [20,...arr1,...arr2];  //[20,1,2,5,6]
console.log(newArr);

三、替代es5的apply方法es5

// ES5 的寫法  
function f(x, y, z) {  
// ...  
}  
var args = [0, 1, 2];  
f.apply(null, args);  
// ES6 的寫法  
function f(x, y, z) {  
// ...  
}  
var args = [0, 1, 2];  
f(...args);  

四、求最大值Math.max()spa

// ES5 的寫法  
Math.max.apply(null, [14, 3, 77])  
// ES6 的寫法  
Math.max(...[14, 3, 77])  
//  等同於  
Math.max(14, 3, 77);  

經過push函數,將一個數組添加到另外一個數組的尾部prototype

// ES5 的寫法  
var arr1 = [0, 1, 2];  
var arr2 = [3, 4, 5];  
Array.prototype.push.apply(arr1, arr2);  
// ES6 的寫法  
var arr1 = [0, 1, 2];  
var arr2 = [3, 4, 5];  
arr1.push(...arr2);  

新建Date類型rest

// ES5  
new (Date.bind.apply(Date, [null, 2015, 1, 1]))  
// ES6  
new Date(...[2015, 1, 1]);  

與解構賦值結合,生成新數組code

// ES5  
a = list[0], rest = list.slice(1)  
// ES6  
[a, ...rest] = list 
下面是另一些例子。  
const [first, ...rest] = [1, 2, 3, 4, 5];  
first // 1  
rest // [2, 3, 4, 5]  
const [first, ...rest] = [];  
first // undefined  
rest // []:  
const [first, ...rest] = ["foo"];  
first // "foo"  
rest // [] 

將字符串轉爲真正的數組

[...'hello']  
// [ "h", "e", "l", "l", "o" ]  

將實現了 Iterator 接口的對象轉爲數組

var nodeList = document.querySelectorAll('div');  
var array = [...nodeList];  
相關文章
相關標籤/搜索