4 ms·
What does […Array mean in this context? Does it create an array?
by prox 4y ago
What does […Array mean in this context? Does it create an array?
- bambax 4y agoYes it creates an array of length 'clicks'; so for example [...Array(2)] creates the array [undefined, undefined]. It's just a way to do a loop without writing a for loop and use forEach instead.
- monkpit 4y agoProbably a shortcut for Array(n).fill()
- manbash 4y agoThe "..." is called a spread operator in javascript. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe... (In python there is the "*" operator which should be equivalent: [1, 2, *arr]. Array(clicks) instantiate an array of length 'clicks', with its elements undefined. Then "[...Array(clicks)]" takes the above array instance and spreads it as content in another array. Seems redundant and they could've just used Array(clicks).
- tuukkah 4y ago> Array(clicks) instantiate an array of length 'clicks', with its elements undefined. Not undefined elements but no elements, or "empty" elements. > they could've just used Array(clicks). No, because the following forEach call does nothing for such an array. You need to fill the array first with Array(clicks).fill() or shorter, [...Array(clicks)]
- tuukkah 4y ago... is the spread syntax, which is a neat way to use the entries of an existing array or object in an argument list or within an array or object literal. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe... Array(length) creates an array that has a length but no elements (or weird, "empty" elements). The square brackets create a new array [...Array(length)] which will have undefined elements instead, as trying to access an "empty" element returns undefined. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guid...
- prox 4y agoThat is neat! Thanks!