ES6-assignment-rest-spread operator

1. ES6 allows assigning initial values ​​to function parameters.

  1. The initial value of a formal parameter, a parameter with a default value, is generally placed at the back. If the value is assigned, the assigned value is used, and the default value is used if it is not assigned.
   <script>
        function fun(a,b,c=3){
    
    
           return a+b+c;
        }
        let result=fun(1,2,10);
        console.log(result);//13
    </script>
  1. Combined with deconstruction assignment
 // function fun2(options){//这种方法输出有重复
        //   console.log(options.name);
        //   console.log(options.age);
        // }

        function fun2({
    
    name,age}){
    
    //与解构赋值相结合
             console.log(name);
             console.log(age);
        }
        fun2({
    
    
            name:"sun",
            age:18,
        });

2. ES6 introduces the rest parameter, which is used to obtain the actual parameters of the function, instead of arguments.

How to use: ...标识符Put it in the position of the actual parameter

function date(...args){
    
    
console.log(args);
}
date('aa','bb');

Note: The rest parameter must be put at the end of the parameter, in the case of multiple parameters.

Three, spread operator

  1. [...] The spread operator can convert [array] into a comma-separated [parameter sequence]
 const str=['孙悟空','猪八戒','沙和尚'];
        function fun(){
    
    
            console.log(arguments);
        }
        fun(...str);//等同于fun(孙悟空,猪八戒,沙和尚)

2. Application of spreading operator
(1) Merging of arrays

 const name=["孙悟空","沙和尚","猪八戒"]
        const age=[18,19,20]
        //数组的合并
        //const per=name.concat(age);
        //运用扩展运算符
        const per=[...name,...age]
        console.log(per);

(2) Cloning of the array

//数组克隆
        const per=[...name];
        console.log(per);

(3) Convert the pseudo-array to a real array

 //将伪数组转换为真正的数组
        const per=document.querySelectorAll('div');//查找所有的div元素
        const perArr=[...per]
        console.log(perArr);

Guess you like

Origin blog.csdn.net/weixin_45636381/article/details/113938460