ES6 之 函數擴展(擴展運算符)

擴展運算符是三個點(…),好比rest參數的逆運算,講一個數組轉爲用逗號分隔的參數序列

console.log(...[1, 2, 3]);      //1 2 3

console.log(1,...[2,3,4],5);    //1 2 3 4 5

console.log([...document.querySelectorAll('div')]);     //[div, div, div]


# 將一個數組變爲參數序列

function push(array, ...items){
    array.push(...items);
    return array;
}
var arr = [1,3];
console.log(push(arr, 1, 3, 4));        //[ 1, 3, 1, 3, 4 ]


function add(x, y) {
    return x + y;
}
var number = [4,38];
console.log(add(...number)) //42

# 替代數組的apply的方法
//es5
function f(x,y,z) {}
var arr = [0,1,2];
f.apply(null,arr);

//es6
f(...arr);

#使用Math簡化數組取最大值
console.log(Math.max.apply(null, [14, 3, 7]));      //14

console.log(Math.max(...[14, 3, 7]));               //14

# push函數將一個數組添加到另一個數組尾部(親測不行)
var arr1=[0,1,2];
var arr2 =[3,4,5];

console.log(Array.prototype.push.apply(arr1, arr2));    //親測: 6,並未像文中所說的將一個數組追加到另一個數組尾部

console.log(arr1.concat(arr2));         //[ 0, 1, 2, 3, 4, 5 ]

console.log(arr1.push(...arr2));                        // 親測: 6, 並未像文中所說的將一個數組追加到另一個數組尾部

console.log(new (Date.bind.apply(Date, [null, 2015, 1, 1])));       //2015-01-31T16:00:00.000Z

console.log(new Date(...[2015, 1, 1]));                             //2015-01-31T16:00:00.000Z


# 合併數組
var arr1=[0,1,2];
var arr2 =[3,4,5];

arr1 = arr1.concat(arr2);
console.log(arr1);          //[ 0, 1, 2, 3, 4, 5 ]

console.log([...arr1, ...arr2]);//[ 0, 1, 2, 3, 4, 5 ]

#與解構賦值結合
const [frist, ...rest] = [1,2,3,4,5,6];
console.log(frist); //1
console.log(rest);//[ 2, 3, 4, 5, 6 ]

const [frist, ...rest] = [];
console.log(frist); //undefined
console.log(rest);//[]

const [frist, ...rest] = ["foo"];
console.log(frist); //foo
console.log(rest);//[]

# 類似數組的對象  - Map和Set結構
let map = new Map([
    [1,'one'],
    [2,'two'],
    [3,'three']
])
let arr = [...map.keys()];      //[ 1, 2, 3 ]

# 類似數組的對象  -  Generator函數
var go = function *() {
    yield 1;
    yield 2;
    yield 3;
}
[...go()];      //[1,2,3]

ps:如果沒有對iterator接口的對象使用擴展運算符,將會報錯

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章