[Javascript] ES2015 - Default args, Spread operator

Default args

可以將在function的參數給予預設值

1
2
3
function fnWithDefaultArg(a,b=[]){
// some codes
}

Spread operator

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

1
2
3
4
5
function fn(a,b,c){
// some codes
}
var args = [1,2,3];
fn(...args); <= spread operator

A more powerful array literal

1
2
var parts = ['shoulders', 'knees'];
var lyrics = ['head', ...parts, 'and', 'toes']; // ["head", "shoulders", "knees", "and", "toes"]

A better push

1
2
3
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1.push(...arr2);