一. 函数默认值
ES5 中函数的参数设置不了默认值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| function f(x,y,z) {
if (y === undefined) {
y = 7
}
if (z === undefined) {
z = 42
}
return x+y+z
} console.log(f(1));
|
在 ES6 中函数的参数可以设置默认值
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| function fun(x,y = 7,z=42) {
return x*y+z
}
console.log(fun(1));
console.log(fun(1,undefined,43));
console.log(fun(1,undefined,2));
|
有默认值的参数向后写,没有默认值的参数写在前面。
默认值不仅可以传常数,还可以传表达式,也可以传入 undefined
函数参数里面可以写成表达式
1 2 3 4 5 6 7 8 9 10 11
| function f(x,y,z=x+y) {
console.log(f.length);
return x*10+z
}
console.log(f(1,undefined,2));
|
我们可以获取函数的形参
1 2 3 4 5 6 7 8 9 10 11 12 13
| function f(x,y = 7,z=x+y) {
console.log(Array.from(arguments));
return x*10+z
}
console.log(f(1,undefined,2));
|
也可以获取函数的实参个数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| function f(x,y = 7,z=x+y) {
console.log(f.length);
return x*10+z
}
console.log(f(1,undefined,2));
console.log(f(1,2,3,4))
|
二. 不确定参数
ES5 的做法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| function sum() {
let num=0;
Array.prototype.forEach.call(arguments,function (item) {
num+=item*1
})
return num
}
console.log(sum(1,2,3,4));
|
ES6 的做法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| function sum() {
let num=0;
Array.from(arguments).forEach(function(item){
num+=item*1
})
return num
}
console.log(sum(1,2,3,4));
|
Rest parameter(剩余参数)
剩余参数的作用是将所有的参数储存在这个里面,要用的时候可以采用数组的方式进行遍历。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| function sum(base,...nums) {
let num = 0
nums.forEach(item => {
num+=item*1
});
return base*2+num
}
console.log(sum(1,2,3));
function sum(x=1,y=2,z=3) {
return x+y+z
}
let data = [4,5,9]
console.log(sum(data[0],data[1],data[2]));
console.log(sum.apply(this,data));
console.log(sum(...data));
|
三. 箭头函数
ES5 中定义函数的方式
1 2 3 4 5
| function hello() {}
let hello = function () {}
|
ES6 箭头函数
1 2 3 4 5 6 7
| let hello = name =>{
console.log('hello',name);
}
hello('JavaScript')
|
箭头函数里面的函数体只有一句并且是 return 的时候,可以省略大括号 {}
1 2 3
| let sum = (x,y,z) => x+y+z
console.log(sum(1,2,3));
|
当函数体返回的是对象的时候,要用大括号 ( ) 将其括起来
1 2 3 4 5 6 7 8 9 10 11
| let sum = (x,y,z) => ({
x:x,
y:y,
z:z
})
console.log(sum(1,2,3));
|
或者直接使用简单的方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| let sum = (x,y,z) => {
return {
x:x,
y:y,
z:z
}
}
console.log(sum(1,2,3));
|
函数中 this 的指向
ES5 函数中this定义在函数里面的时候,谁调用这个函数,this就指向谁。
1 2 3 4 5 6 7 8 9 10 11 12 13
| let test ={
name:'test',
say:function () {
console.log(this.name);
}
}
test.say()
|
ES6 中箭头函数的 this 的指向是写在那个地方的指向。
1 2 3 4 5 6 7 8 9 10 11 12 13
| let test ={
name:'test',
say: ()=> {
console.log(this.name);
}
}
test.say()
|
四. 练习
如何使用箭头函数来处理一个数组排序的问题
1 2 3 4 5 6 7 8 9
| let averse = (...nums)=>{
return nums.sort( (a,b) => b-a)
}
console.log(averse(1,3,1,22,3));
|
箭头函数对this的处理还有什么妙用