ES6函数优化

110 阅读1分钟

函数优化

1.直接给参数写上默认值,没传就自动采用默认值
2.可以传任意参数
3.箭头函数
4.箭头函数+箭头表达式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width= device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        //在ES6以前,无门无法给一个函数参数设置默认值,只能采取变通的方法
        function add(a,b){
            b=b||1;
            return a+b;
        }
        
        console.log(add(10));

        //现在可以这么写,直接给参数写上默认值,没传就自动采用默认值
        function add2(a,b=1){
            return a+b;
        }
        console.log(add2(1));


        // 可以传任意参数
        function fun(...values){
           console.log(values.length);
        }

        fun(1,2,3);
        fun(1,2);

        //箭头函数
        //以前 
        var print=function(obj){
            console.log(obj);
        }

        //现在
        var print1=obj => console.log(obj);
        print1("hello");

        var sum=(a,b)=>a+b;
        console.log(sum(3,4));

        var sum2=(a,b) =>{
            c=a+b;
            return c+a;
        }
        console.log(sum2(2,3));


        const person={
            name: "rider",
            age: 21,
            language: ['java','c','c++']
        }


        //以前
        function hello(person){
            console.log("hello"+person.name);
        }
        
        //箭头函数+箭头表达式
        var hello2= ({name}) => console.log("hello,"+name);
        hello2(person);
    </script>
</body>
</html>