javascript - How does the spread operator in ES6 JS work as a function argument? -


ok, i'm trying understand how new spread works function parameter. imagine function unknown number of parameters , adds them together.

let addnums = ...a => a.reduce ((a,b) => a+b); 

this function works. so, what's problem? here's observations, followed problem:

  1. the spread operator function parameter / argument seems designed 'spread' array of values separate arguments:

based on research i've done, spread operator can used pass arrays functions not accept arrays arguments standard, e.g. array.prototype.push(), without having use apply:

var x = []; var y = [1,2,3]; // array.push(arg1,arg2,...) requires separate arguments possible: x.push(...y); // 'spreads' 'y' separate arguments: x.push (arg1,arg2,...) 

but array passed push in case needs declared/defined beforehand (in case y)

  1. this confirmed looking @ length of arguments object inside function

if use addnums(1,2,3,4), arguments.length still == 4. so, seems function still being called addnums(1,2,3,4)

the problem

my problem i'm not calling addnums array argument spread operator process. i'm not calling addnums([1,2,3,...]) behaviour i'm struggling understand there seems secret hidden step where, given function declared spread operator single argument:

let x =  ...somesetofvalues => return ; 

and called list of arguments:

x(1,2,3,4,...); 

there's generation of arguments object and variable of type array also created same name function parameter spread operator.

perhaps obvious or trivial more experience coders, seems me counter-intuitive use cases put forward far spreading array of values across set of parameters of unknown length.

in fact, go far rather reading , splitting array across parameters, when function called multiple parameters, defined single parameter spread operator, spread operator acts similar : array.apply(null, arguments) or var = [arg1, arg2, ...] - ** creator not spreader **

sources research: http://es6-features.org/#spreadoperator https://developer.mozilla.org/en/docs/web/javascript/reference/operators/spread_operator spread operator es6 - particularly comment on question "@void use in function calls, i.e. if myfunc takes unknown number of arguments, can give arguments array spread. this: myfunc(...dynamicallygeneratedargs)"

after doing more research, able find reference called rest parameters.

rest parameters use ... spread operator part of parameter, behave differently. in fact collect indefinite number of arguments/parameters , make them available array inside function.

source: link mdn description of 'rest' parameters

basically behaviour observed in first place!


Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -