Spread Syntax vs Rest Parameter in ES2015 / ES6

前端 未结 10 1815
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 10:52

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

10条回答
  •  伪装坚强ぢ
    2020-11-27 11:19

    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'];

    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;

提交回复
热议问题