欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

ES6新手指南:深入理解rest运算符

最编程 2024-08-05 11:30:25
...

rest运算符也是三个点号,不过其功能与扩展运算符恰好相反,把逗号隔开的值序列组合成一个数组。

//主要用于不定参数,所以ES6开始可以不再使用arguments对象
var bar = function(...args) {
    for (let el of args) {
        console.log(el);
    }
}
bar(1, 2, 3, 4);
//1
//2
//3
//4

bar = function(a, ...args) {
    console.log(a);
    console.log(args);
}
bar(1, 2, 3, 4);
//1
//[ 2, 3, 4 ]

rest运算符配合解构使用:

var [a, ...rest] = [1, 2, 3, 4];
console.log(a);//1
console.log(rest);//[2, 3, 4]

推荐阅读