【ES6】函数——笔记1

67 阅读2分钟

一、函数参数默认值可以与解构赋值的默认值的结合(易乱)

注意:通常情况下,函数的默认值参数是尾参数。

    function fun1({x="x",y="y"}={}){
        console.log(x,y);
    }
    function fun2({x,y}={x:"x",y:"y"}){
        console.log(x,y);
    }
    //执行默认参数
    fun1()//x y
    //解构
    fun2()//x y

    fun1({x:"X",y:"Y"})//X Y
    fun2({x:"X",y:"Y"})//X Y

    fun1({x:"X"})//X y
    fun2({x:"X"})//X undefined

    fun1({})//x y
    fun2({})//undefined undefined

使用于函数里指定参数是否可以省略,如果默认参数设置为undefined表示这个参数可以省略。

二、rest参数【以逗号分隔的参数转换为数组】

1、格式

...变量名

    function getList(...list){
        console.log(list);//Array(4) [ 1, 2, 3, 4 ]
     }
     getList(1,2,3,4)

2、作用

用于获取函数多余的参数,参数以数组的形式存储,不需要使用arguments。

使用rest写法

const s = (...numbers) => numbers.sort();
console.log(s(1,3,4,1,2));//Array(5) [ 1, 1, 2, 3, 4 ]

使用argument写法【Array.from(arguments)是把arguments转为数组形式】

function s(){
        return Array.from(arguments).sort()
    }
   console.log( s(1,6,1,2,4,2,3));//Array(7) [ 1, 1, 2, 2, 3, 4, 6 ]

3、注意

函数里rest必须是尾参数,否则会报错。

三、箭头函数(常用)

1、使用"=>"定义函数

let f=v=>v
console.log(f(1));//1

以上代码等价于

     function f(v){
        return v
    }
    console.log(f(1));//1

2、传入两个参数使用“()”圆括号包裹变量

let f=(x,y)=> `x=${x};y=${y}`
console.log(f(1,2));//x=1;y=2

3、当返回的数据是对象形式时也要用“()”圆括号包裹返回的对象

let f=(x,y)=>({x:x,y:y})
console.log(f(1,2));//Object { x: 1, y: 2 }

4、箭头函数与map的使用

const arr=[1,2,3].map(x=>x+2)
console.log(arr);//Array(3) [ 3, 4, 5 ]

5、箭头函数与数组排序

    let arr=[2,1,2,12,3,45,0]
    // 小到大
    console.log(arr.sort((a,b)=>a-b));//Array(7) [ 0, 1, 2, 2, 3, 12, 45 ]
    // 大到小
    console.log(arr.sort((a,b)=>b-a));//Array(7) [ 45, 12, 3, 2, 2, 1, 0 ]

6、注意事项(前端面试常问)

1、没有自己的this对象。 2、箭头函数能使用arguments,可以使用rest。 3、不是构造函数不能使用new。 4、不能使用yield命令,不能被当做Generator函数。

四、尾递归

计算n阶层,递归需要保存n个元素复杂度为O(n),尾递归只保留last的调用记录,复杂度为O(1)。 递归:函数调用自身【栈溢出】;

function f(n){
        if(n === 1) return 1;
        return n*f(n-1)
    }
    console.log(f(3));//6

尾递归:函数尾部调用自身。

 function f(n, last) {
        if (n === 1) return last
        return f(n - 1, last * n)
    }
    console.log(f(3, 1));