javascript - Access to ES6 array element index inside for-of loop -
we can access array elements using for-of loop:
for (const j of [1, 2, 3, 4, 5]) { console.log(j); }
how can modify code access current index too? want achieve using for-of syntax, not foreach or for-in.
use array.prototype.keys
:
for (const index of [1, 2, 3, 4, 5].keys()) { console.log(index); }
if want access both key , value, can use array.prototype.entries()
destructuring:
for (const [index, value] of [1, 2, 3, 4, 5].entries()) { console.log(index, value); }
wiki
Comments
Post a Comment