1.参数的默认值
简单直观的功能参数默认值
ECMAScript 6
function f (x, y=7, z=42) {
return x + y + z
}
f(1) === 50
ECMAScript 5
function f (x, y, z) {
if(y === undefined)
y = 7;
if(z === undefined)
z = 7;
return x + y + z;
};
f(1) === 50;
闲置参数
将剩余参数聚合为可变函数的单个参数
ECMAScript 6
function f (x, y, ...a) {
return (x + y) * a.length
}
f(1, 2, "hello", true, 7) === 9
ECMAScript 5
function f(x,y){
var a = Array.prototype.slice.call(arguments, 2);
return (x + y) * a.length;
}
f(1, 2, "hello", true, 7) === 9;
3.参数传递
将可迭代集合的元素(如数组或甚至字符串)传递到文字元素和单个函数参数中。
ECMAScript 6
var params = ["hello", true, 7]
var other = [1,2, ...params]//[1, 2, "hello", true, 7]
function f (x,y, ...a) {
return (x + y) * a.length
}
f(1,2, ...params) === 9
var str = "foo"
var chars = [...str]// ["f","o","o"]
ECMAScript 5
var params = ["hello", true, 7]
var other = [1, 2].concat(params);//[1, 2, "hello", true, 7]
function f(x,y){
var a = Array.prototype.slice.call(arguments, 2);
return (x + y)* a.length;
}
f.apply(undefined, [1,2].concat(params)) === 9;
var str = "foo";
var chars = str.split("");// ["f","o","o"]