箭头函数

  1. 有且仅有1个参数,()可以省
  2. 如果函数体只有一句话,而且是return,{}可以省
  3. this 相当于回调外层的this
  1. let add = (a,b)=>{
  2. return a+b;
  3. }
  4. console.log(add(2,3)) //5
  5. let add1 = (a,b)=>a+b
  6. console.log(add1(2,3)) //5
  7. let add2 = a=>a+2
  8. console.log(add2(2)) // 4
  9. var obj = {name:'yk'}
  10. function foo(){
  11. var id = 2
  12. var that = this
  13. console.log(that.name) //yk
  14. setTimeout(() => {
  15. console.log(this===that) //true
  16. console.log(this.name) //yk
  17. }, 100);
  18. }
  19. foo.call(obj); //true

默认参数

  1. let add3 = (a=1,b=2,c=3)=>a+b+c
  2. console.log(add3()) //6
  3. console.log(add3(2,3)) //8
  1. function fn({title='a'}={title:'b'}){
  2. console.log(title)
  3. }
  4. fn()
  5. b
  6. fn(1)
  7. a
  8. fn({name:'11'})
  9. a
  10. fn({})
  11. a

参数展开

function(a,b,...名字) 名字自定义
剩余参数必须在参数列表的最后

  1. let add4 = (a,b,...args)=>{
  2. console.log(a,b,args)
  3. return Math.max(...args)
  4. }
  5. add4(1,2,3,4,5,5,6,8)
  6. // 1 2 [ 3, 4, 5, 5, 6, 8 ]
  7. let add5 = (a,b,...args,c)=>{
  8. console.log(a,b,args,c)
  9. } //Rest parameter must be last formal parameter
  10. add4(1,2,3,4,5,5,6,8,111)
  11. let sort = (a,b,...args)=>{
  12. console.log(args.sort())
  13. }
  14. add4(1,2,4,2) //2,4

用途

  • 接收剩余参数
  • 展开数组
  1. let arr = [1,2,3]
  2. let arr2 = [1,2,...arr,3]
  3. console.log(arr2) //[ 1, 2, 1, 2, 3, 3 ]
  4. function show1(...args){
  5. show2(...args)
  6. }
  7. function show2(a,b){
  8. console.log(a,b)
  9. }
  10. show1(1,2) //1,2