Usage of rest parameter and spread operator in javascript

后端 未结 6 1875
时光取名叫无心
时光取名叫无心 2020-11-30 05:15

What\'s the usage of rest parameter that will be added in ECMAScript 6?

For example, in ECMAScript 5 you can do the following to get an array of parameters starting

6条回答
  •  爱一瞬间的悲伤
    2020-11-30 05:39

    In your given example, you directly pass the object literal. Whilst still semantic, it seems un-analogous to the application of the spread operator. IMO, the spread operator's value becomes apparent when listing each parameter would determent code readability (and maintainability, when replacing traditional push, splice, concat methods).

    With spread operator

    let nums = [1.25,5.44,7.15,4.22,6.18,3.11];   
    
    function add(a, b, ...nums){
      let sum = parseInt(a + b);
      nums.forEach(function(num) {
        sum += num;
      })
      return parseInt(sum);
    }
    
    console.log(add(1, 2, ...nums)); //30
    

    ES6Fiddle demo (compiled by traceur-compiler)

    Without spread operator

    var nums = [1.25,5.44,7.15,4.22,6.18,3.11];   
    
    function add(a, b, nums){
      var sum = parseInt(a + b);
      nums.forEach(function(num) {
        sum += num;
      })
      return parseInt(sum);
    }
    
    console.log(add(1, 2, nums)); //30
    

    JSFiddle demo

    In closing, I don't think that using the spread operator will improve or impede performance, it does however offer improved code readability, and arguably maintainability too. Regrettably, ES6 isn't widely implemented yet, and I'll assertively speculate that it will take sometime for browser support to ensue.

    Fun fact: PHP 5.6 introduces similar functionality with its variadic functions which will make func_get_args() redundant.

提交回复
热议问题