Abdennour TOUMI Abdennour TOUMI - 1 year ago 98
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 :

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 Source

Use Array.prototype.keys:

[for (j of [1,2,3,4,5].keys()) (j<3)?0:1]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download