Abdennour TOUMI Abdennour TOUMI - 2 months ago 6
Javascript Question

Access to ES6 array element index inside for-of loop

[for (j of [1,2,3,4,5]) j+1]


The above instruction build an array like so :
[2,3,4,5,6]


however , we need to access to index of each element

Pseudo Code (wanted) :



[for ([j,index] of [1,2,3,4,5]) (index<3)?0:1]
//Expected OUTPUT : [0,0,1,1,1]


How to do this using for-of syntax , not forEach neither for-in ?

Answer

Use Array.prototype.keys:

[for (j of [1,2,3,4,5].keys()) (j<3)?0:1]
Comments