ES2015 / ES6中的Spread语法与Rest参数 [英] Spread Syntax vs Rest Parameter in ES2015 / ES6

查看:131
本文介绍了ES2015 / ES6中的Spread语法与Rest参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对ES2015中的spread语法和rest参数感到困惑。任何人都可以通过适当的例子解释它们之间的区别吗?

I am confused about the spread syntax and rest parameter in ES2015. Can anybody explain the difference between them with proper examples?

推荐答案

使用spread时,您正在将单个变量扩展为更多:

When using spread, you are expanding a single variable into more:

var abc = ['a', 'b', 'c'];
var def = ['d', 'e', 'f'];
var alpha = [ ...abc, ...def ];
console.log(alpha)// alpha == ['a', 'b', 'c', 'd', 'e', 'f'];

使用rest参数时,您将函数的所有剩余参数折叠为一个数组:

When using rest arguments, you are collapsing all remaining arguments of a function into one array:

function sum( first, ...others ) {
    for ( var i = 0; i < others.length; i++ )
        first += others[i];
    return first;
}
console.log(sum(1,2,3,4))// sum(1, 2, 3, 4) == 10;

这篇关于ES2015 / ES6中的Spread语法与Rest参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆