262 ES6 ...运算符:扩展运算符、剩余参数(★★)

剩余参数语法允许我们将一个不定数量的参数表示为一个数组,不定参数定义方式,这种方式很方便的去声明不知道参数情况下的一个函数。
用来取代arguments,但比arguments灵活, 只能是最后部分形参参数。
【箭头函数中,不能使用arguments,报错未定义。】

function sum (first, ...args) {
     console.log(first); // 10
     console.log(args); // [20, 30] 
     console.log(arguments); // Arguments(3) [10, 20, 30, ...]
 }
 sum(10, 20, 30)
const sum = (...args) => {
	let total = 0;
	args.forEach(item => total += item);
	return total;
};

console.log(sum(10, 20));  // 30
console.log(sum(10, 20, 30));  // 60 

剩余参数和解构配合使用

let students = ['wangwu', 'zhangsan', 'lisi'];
let [s1, ...s2] = students; 
console.log(s1);  // 'wangwu' 
console.log(s2);  // ['zhangsan', 'lisi']

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>07_3点运算符</title>
</head>

<body>
    <!--
        * 用途
        1. rest(可变)参数
            * 用来取代arguments,但比arguments灵活,只能是最后部分形参参数
            function add(...values) {
                let sum = 0;
                for(value of values) {
                sum += value;
                }
                return sum;
            }
            
        2. 扩展运算符
            let arr1 = [1,3,5];
            let arr2 = [2,...arr1,6];
            arr2.push(...arr1);
    -->

    <script type="text/javascript">
        function fun(a, b, ...values) {
            console.log(arguments); // 伪数组[1, 2, 3, 4, 5, 6]
            //        arguments.forEach(function (item, index) {
            //            console.log(item, index);
            //        });
            console.log(values); // [3, 4, 5, 6]
            values.forEach(function(item, index) {
                console.log(item, index);
            })
        }
        fun(1, 2, 3, 4, 5, 6);

        let arr = [2, 3, 4, 5, 6];
        let arr1 = ['abc', ...arr, 'fg'];
        console.log(arr1); // ["abc", 2, 3, 4, 5, 6, "fg"]
    </script>

</body>

</html>
原文地址:https://www.cnblogs.com/jianjie/p/12236717.html