Spread Syntax vs Rest Parameter in ES2015 / ES6

前端 未结 10 1756
隐瞒了意图╮
隐瞒了意图╮ 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:21

    ES6 has new feature three dots ...

    Here is how we can use these dots:

    1. As Rest/Collector/Gather
    var [c, ...m] = [1,2,3,4,5]; // m -> [2,3,4,5]
    

    Here ...m is a collector, it collects the rest of the parameters. Internally when we write:

    var [c, ...m] = [1,2,3,4,5]; JavaScript does following

    var c = 1,
        m = [2, 3, 4, 5];
    
    1. As Spread
    var params = [ "hello", true, 7 ];
    var other = [ 1, 2, ...params ]; // other => [1,2,"hello", true, 7]
    

    Here, ...params spreads so as to adding all of its elements to other

    Internally JavaScript does following

    var other = [1, 2].concat(params);
    

    Hope this helps.

提交回复
热议问题