JavaScript ES6中的剩余参数

前端 · 2020-08-18 ·

剩余参数语法允许我们将一个不定数量的参数表示为一个数组。

当函数实参个数大于形参个数时,我们可以将剩余的实参放到一个数组中。

// 剩余参数 first,args形参,10,20,30,40 实参
function sum(first, ...args) {
    console.log(first); // 10
    console.log(args); // [20,30,40]
}
sum(10, 20, 30, 40);
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 = ["zhao", "qian", "sun", "li"];
let [s1, ...s2] = students;
console.log(s1); // zhao
console.log(s2); //["qian", "sun", "li"]
%