ES6-函数默认参数、rest参数、扩展运算符

ES6允许给函数的参数设置初始值

形参默认值

如果实参传了就用实参的值,如果实参没传就用形参的默认值的值。

潜规则:具有默认值的参数,一般位置比较靠后

        function add(a=1,b=2,c=3){
    
    
           return a+b+c
        }
        let result = add(4,5)
        console.log(result)

输出:12

默认值与解构赋值结合

        // 默认值与解构赋值结合
        function connect ({
    
    host='127.0.0.1',username='root',password='123456',port='3306'}){
    
    
            console.log(host),
            console.log(username),
            console.log(password)
            console.log(port)   
        }
        /*
        正常写法
        function connect (options){
           console.log(options.host)
           console.log(options.username)
           console.log(options.password)
           console.log(options.port)   
        }*/
        connect({
    
    
            host:'localhost',
            username:'root',
            password:'root',
            port:3306
        })

输出:
在这里插入图片描述

rest参数

ES6引入 rest参数,用于获取函数的实参,用来代替arguments。
rest参数:需要在函数的最后一个参数后面添加 ...agrs
rest参数和arguments相比,rest参数返回的是一个数组,arguments返回的是对象。

eg:
arguments

        function data (){
    
    
            // ES5的arguments
           console.log(arguments)    
        }
        data('孙悟空','猪八戒','唐僧','沙和尚')

在这里插入图片描述
rest:

        function data (a,b,...args){
    
    
            console.log(a)
            console.log(b)
            console.log(args)       
        }
        data('孙悟空','猪八戒','唐僧','沙和尚')

在这里插入图片描述
==注意: == rest参数必须要放到参数最后

扩展运算符

...扩展运算符能将数组转换为逗号分隔的参数序列。

使用方式

扩展运算符常在实参之前使用。
eg:

   const peoples = ['孙悟空','猪八戒','唐僧','沙和尚']
   console.log(peoples)
   console.log(...peoples)

   function xiyouji (){
    
    
      console.log(arguments)
   }
   xiyouji(peoples)
   xiyouji(...peoples)

输出:
在这里插入图片描述

扩展运算符应用

  • 数组合并
    格式:新数组 = [...数组1,...数组2]
 const shitu = ['孙悟空','猪八戒','唐僧','沙和尚']
 const yaojing = ['白骨精','玉兔精','蜘蛛精']
 const xiyouji = [...shitu,...yaojing]
 /*也可以使用数组的方法进行拼接
 const xiyouji = shitu.concat(yaojing) */
 console.log(xiyouji)

在这里插入图片描述

  • 数组克隆
    格式:新数组 = [...数组名]
        const shitu = ['孙悟空','猪八戒','唐僧','沙和尚']
        const xiyouji = [...shitu]
        console.log(xiyouji)

在这里插入图片描述

  • 将伪数组转换为真正的数组
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div></div>
    <div></div>
    <div></div>
    <script>
        const divs = document.querySelectorAll('div');
        console.log(divs)
        const divArr = [...divs]
        console.log(divArr)
    </script>
</body>
</html>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/mantou_riji/article/details/124779048