1、为函数参数指定默认值
function fn(a = 10, b =20){
console.log(a + b); // 30
}
fn()
2、函数的 rest 参数
rest 参数形式为(“…变量名”),用于获取函数的多余参数,这样就不需要使用 arguments 对象了。rest 参数搭配的变量是一个数组,该变量将多余的参数放入数组中。
function sum(){
var args = arguments;
var res = 0;
for(var i = 0; i<args.length;i++){
res += args[i];
}
console.log(res);
}
sum(1,2,3,4,5,6)
更改后
function sum(...arr){
var res = 0;
for(var i=0; i<arr.length;i++){
res += arr[i];
}
console.log(res);
}
sum(10,1,2,3,4,5)
3、箭头函数
使用箭头 “=>”定义函数
const fn = a => a;
const fn2 = function (a){
return a;
};
console.log(fn(1));
console.log(fn(2));
```javascript
const fn = (a, b) => a + b;
console.log(fn(1, 2)); // 3
const fn = (a, b) => {
a = a * 2;
b = b * 3;
return a + b;
};
console.log(fn(1, 2)); // 6
箭头函数体内没有自己的 this 对象,所以在使用的时候,其内部的 this 就是定义时所在环境的对象,而不是使用时所在环境的对象。
不能给箭头函数使用 call apply bind 去改变其内部 this 的指向
箭头函数体内没有 arguments 对象,如果要用,可以用 Rest 参数代替,
function fn (){
setTimeout(() => {
console.log(arguments);
},1000)
}
fn(1,2,3)
不能当作构造函数,不能使用 new 命令,否则会抛出一个错误。
const Fn = (a, b) => a + b;
const f = new Fn(1, 2);
箭头函数不能用作 Generator