Array.from({length: num+1}, (v, k) => k).slice(2);
I’m just curious how this code works specially the Array.from({length: num+1}....
part.
Array.from({length: num+1}, (v, k) => k).slice(2);
I’m just curious how this code works specially the Array.from({length: num+1}....
part.
Array.from takes two arguments and creates an array.
length
property, so if you do Array.from({length: 10})
, you’re saying create an array from an object with a length
of 10, so you’ll get an array of length 10 out of the other end.map
, so have a read up on that if you’re not quite sure what it’s doing . v is the current value, and k is the current index, and the map is saying just return the index. SoArray.from({length: 5}, (v, i) => i)
Will create an array of length 5, and each value will be the index, so you get:
[0,1,2,3,4]
Edit: re arrays being objects:
[ , , , , ,]
Is basically the same as
{length: 5}
And
[1,1,1,1,1]
basically the same as
{0: 1, 1: 1, 2: 1, 3: 1, 4: 1, length: 5}
If you put those objects into Array.from, you should see those arrays come out the other end