262 ES6剩余参数(★★)

剩余参数语法允许我们将一个不定数量的参数表示为一个数组,不定参数定义方式,这种方式很方便的去声明不知道参数情况下的一个函数。

【箭头函数中,不能使用arguments。】

function sum (first, ...args) {
     console.log(first); // 10
     console.log(args); // [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']

猜你喜欢

转载自www.cnblogs.com/jianjie/p/12236717.html
今日推荐