7 ms·
Can someone explain what the "spread operator" is and how to use it?
by limsup 12y ago
Can someone explain what the "spread operator" is and how to use it?
- heydenberk 12y agoSpread is like python's *args. Instead of this: var mapArgs = function() { var args = Array.prototype.slice.call(arguments, 0, arguments.length - 1); var mapper = Array.prototype.slice.call(arguments, arguments.length - 1); return args.map(mapper); }; You can do this: var mapArgs = function(...args, mapper) { return args.map(mapper); }; And you can also use it to apply. Instead of: var max = Math.max.apply(null, [1, 2, 3, 4]); You can do: var max = Math.max(...[1, 2, 3, 4]);
- jbaudanza 12y agohttps://gist.github.com/sebmarkbage/07bbe37bc42b6d4aef81 https://gist.github.com/sebmarkbage/07bbe37bc42b6d4aef81
- claar 12y agoWow, the example in that gist: var component = <Component {...props} foo={'override'} />; Wha?? For me, there's a point in a language where the benefits of syntactic sugar are outweighed by readability concerns.
- jxm262 12y agoheydenberk explained it well, but just to add some clarity on why you'd want to use prototype.apply for array as an argument - http://stackoverflow.com/questions/2856059/passing-an-array-as-a-function-parameter-in-javascript http://stackoverflow.com/questions/2856059/passing-an-array-... http://stackoverflow.com/questions/1316371/converting-a-javascript-array-to-a-function-arguments-list http://stackoverflow.com/questions/1316371/converting-a-java... https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe... I'm still learning more about JS and so I'm no expert, but it seems to be similar in concept to use the ... in other languages. I think Groovy has something similar and Java has the varargs. They have obvious differences, but conceptually I think of it as passing in a variable number of args.