This question already has an answer here:
What is the best way to do the below in more functional way (with ES6/ES7)
let cols = [];
for (let i =0; i <= 7; i++) {
cols.push(i * i);
}
return cols;
I tried like,
return [ ...7 ].map(i => {
return i * i;
});
but that translated to
[].concat(7).map(function (n) {
return n * n;
});
which is not what I expected.
EDIT:
@pavlo. Indeed, that was a mistake. I was using JSX, and for example, I want 7 divs, (untested)
let cols = [];
for (let i =0; i <= 7; i++) {
cols.push(<div id={i}> ... </div>)
}
return cols;
so the idea was indeed to reduce the number of temp variables and procedural feel.
ES7 Proposal
You can always use something like:
Running this code on Firefox:
This works on Firefox (it was a proposed ES7 feature), but it has been dropped from the spec. IIRC, Babel 5 with "experimental" enabled supports this.
This is your best bet as array-comprehension are used for just this purpose. You can even write a range function to go along with this:
Then you can do:
ES6
A nice way to do this any of:
This will output:
Here's an approach using generators:
Then you can write
Another idea is:
Array(5)
creates an unfilled five-element array. That's howArray
works when given a single argument. We use the spread operator to create an array with five undefined elements. That we can then map. See http://ariya.ofilabs.com/2013/07/sequences-using-javascript-array.html.Alternatively, we could write
or, we could take advantage of the second argument to
Array#from
to skip themap
and writeA horrible hack which I saw recently, which I do not recommend you use, is
One can create an empty array, fill it (otherwise map will skip it) and then map indexes to values: