1. 程式人生 > >4.ES6-剩餘引數、拓展運算子,以及物件合併的方法(含ES7)

4.ES6-剩餘引數、拓展運算子,以及物件合併的方法(含ES7)

剩餘引數

語法:…rest
作用:將引數轉成陣列傳入函式

當我傳入指定個數引數時:

function sum(initVal,a,b,c){
    return initVal + a + b + c;
}
sum(10,9,8,7);//34

當我傳入不定個數引數時:

function sum(initVal,...rest){
    return rest.reduce(function(val,item,index,origin){
        return val + item;
    },initVal)
}
sum(10,9,8
,7);//34 sum(10,9,8,7,6);//40

上例中reduce方法詳見:>>傳送門<<

拓展運算子

語法:…arr
將陣列轉成元素列表

let arr0 = [1,2,3];
let arr1 = [4,5,6];
let arr2 = [...arr0,...arr1];//[1,2,3,4,5,6]
如何合併兩個物件

方法一:迴圈遍歷

let obj1 = {name:'a',age:18};
let obj2 = {name:'b',gender:'man'};
let obj3 = {};
for(var attr in
obj1){ obj3[attr] = obj1[attr]; } for(var attr in obj2){ obj3[attr] = obj2[attr]; } console.log(obj3);//{name: "b", age: 18, gender: "man"}

方法二:assign

let obj1 = {name:'a',age:18};
let obj2 = {name:'b',gender:'man'};
let obj3 = {};
Object.assign(obj3,obj1,obj2);
console.log(obj3);//{name
: "b", age: 18, gender: "man"}

方法三:ES7的物件的拓展運算和ES6的解構賦值

let obj1 = {name:'a',age:18};
let obj2 = {name:'b',gender:'man'};
let obj3 = {...obj1,...obj2};
console.log(obj3);//{name: "b", age: 18, gender: "man"}