JavaScript - js进阶 -剩余运算

剩余运算符

通过 ...符号来获取剩下的参数

<!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>剩余运算</title>
    </head>
    <body></body>
    <script>
        // 剩余运算: 将剩下的数据放到一个变量中

        // 1. 用于收集多余的形参(不确定参数的地方): 使用最多的地方(实际使用还是很少)
        function max(first, ...others) {
            console.log(first, others); // others始终是数组: 哪怕没有数据

            // 剩余运算得到的others数组 与 arguments有何区别?
            // console.log(arguments)

            // others是数组, arguments是伪数组
            // others可以调用数组的任意API, arguments一个都不能调用

            let m = first; // 默认第一个最大

            // 遍历数组: PK
            others.forEach((item) => {
                if (item > m) m = item;
            });

            console.log(m);
        }

        max(1);
        max(1, 2, 3);

        // 2. 用于 解构(不用)
        let arr = "abcdefg".split("");
        let obj = { a: "apple", b: "banana", p: "pitch" };

        let [a, b, ...c] = arr; // 取出第一个和第二个,剩下的都放到c中
        console.log(a, b, c);

        let { p, ...t } = obj; // 取出p放到p变量, 剩下都放t中: 是对象
        console.log(p, t);

        // 3. 打散功能: 用于数组实参( 将数组 变成顺序的参数)
        let res = Math.max(1, 2, 3, 54, 5, 6, 7, 78);
        console.log(res);

        arr = [1, 2, 3, 54, 5, 6, 7, 78];
        // 求数组最大值
        // res = Math.max(arr)             // 系统将数组解析成数字: NaN
        res = Math.max(...arr); // ...arr 将arr的结果变成 1, 2, 3, 54, 5, 6, 7, 78
        // Math.max(1, 2, 3, 54, 5, 6, 7, 78)
        console.log(res);

        // 总结
        // 剩余运算: 一般是给数组用  一个是怎么变成数组(收集剩余的参数: 形参)  和 打散功能( 将数组变成带顺序的 数据 : 实参)
    </script>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Henry_ww

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值