search

Home  >  Q&A  >  body text

Problem with es6 spread operator...

I can understand the expansion character for copying arrays, but I don’t understand the one used to pass parameters to functions

As above, why can function parameters accept several parameters after adding the expansion operator?

fn(...arg)要怎么理解
高洛峰高洛峰2724 days ago994

reply all(8)I'll reply

  • 阿神

    阿神2017-07-05 10:43:47

    When defining a function, this should be called the remaining parameters.

    If the last named parameter of the function is prefixed with..., then when the function is called, the formal parameter will become an array, and the elements in the array will be the values ​​of the extra actual parameters passed to the function.

    See MDN for detailed explanation:
    https://developer.mozilla.org...

    reply
    0
  • 迷茫

    迷茫2017-07-05 10:43:47

    You can take a look at this chestnut first

    The...arg here actually gets the value of arguments, so your method can be rewritten like this

    function fn(){
        var arg = [...arguments];
        console.log(...arg);
    }

    reply
    0
  • PHP中文网

    PHP中文网2017-07-05 10:43:47

    Convert arguments into array

    reply
    0
  • 天蓬老师

    天蓬老师2017-07-05 10:43:47

    Official explanation:

    Bind trailing parameters to an array.

    Used in function parameters, it converts the parameters starting here into an array.

    fn(...args)//所有参数变为数组
    fn(a, ...args)//从第二个参数变为数组

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-07-05 10:43:47

    The formal parameters of the function will be saved in the argument class array. The... operator can convert the class array into an array

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-07-05 10:43:47

    You need to get started with ECMAScript 6

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-07-05 10:43:47

    You can understand that
    fn(...arg) places all the parameters of the parameters in the arg array. No matter how many parameters you pass when you call this function, they can be obtained by arg.

    reply
    0
  • 巴扎黑

    巴扎黑2017-07-05 10:43:47

    Function parameters can be obtained through the array-like object arguments. Any multiple parameters you pass in essentially exist as array-like objects inside the function, so adding the spread operator just turns this array-like object into a parameter sequence

    reply
    0
  • Cancelreply