ECMA Script 6
ES6默认参数
函数形参默认值
function fun(url,timeout=60,callback = () => {})
{
//其余部分
}
url为必须参数,其余为可选。
默认参数对arguments的影响
ES5 严格模式下arguments对象将不会发生变化,ES6中如果参数使用了默认参数,则无论是否使用严格模式,arguments对象都将与ES5严格模式保持一致
对象将与命名参数分离
function mixArg(first,second='b')
{
console.log(arguments.length); // => 1
console.log(arguments[0] === first); // =>true;
console.log(arguments[1] === second); // =>false;
first = 'c';
second = 'd';
console.log(arguments[0] === first); // =>false;
console.log(arguments[1] === second); // =>false;
}
默认参数表达式
默认参数可以使用函数表达式的返回值来确定,这样就可以根据第一(N)个参数返回不同的默认参数值了。
无命名参数
ES5使用arguments来实现对无命名参数的处理,ES6则推荐使用不定参数(如下)来处理。
不定参数
函数命名参数前添加三个点…表明这个是个不定参数,该参数是一个数组,包含所有之后传入的参数。每个函数只能有一个不定参数,且其之后不可有其他参数。
function fun(arg1,...args)
{
console.log(arg1);
for(let test in args)
{
console.log(test);
}
}
fun('hello','this','world',)
输出为hello this world。
无论是否使用不定参数,arguments仍然可用。
展开运算符
举个例子
var arr = [1,2,3,4];
console.log(...arr);//等价于console.log(1,2,3,4)