DEV Community

Discussion on: Problems with Using for...in on Arrays in JavaScript

Collapse
 
lionelrowe profile image
lionel-rowe • Edited

You can also use Array#keys to get an iterator with the array indexes as numbers:

const arr = [1, 2, 3]

for (const i of arr.keys()) {
    console.log(typeof i, i) // number 0, number 1, number 2
}

Similarly, Array#values gives the elements of the array, and Array#entries gives tuples of [index, element]:

for (const [idx, el] of arr.entries()) {
    console.log({ idx, el }) // {idx: 0, el: 1}, {idx: 1, el: 2}, {idx: 2, el: 3}
}
Collapse
 
imjoshellis profile image
Josh Ellis • Edited

Awesome! I didn't put 2 + 2 that .keys() and .entries() would work on arrays (I use them all the time for objects), that's great.

Collapse
 
lionelrowe profile image
lionel-rowe

It's a little different from Object.keys and so on. You can do Object.keys(arr) too, but then you'll get an array of string keys, rather than an iterator of number keys. Interestingly, there's no such thing as Object#keys — I guess it doesn't make sense to return an iterator of keys for something that itself isn't iterable.

Thread Thread
 
imjoshellis profile image
Josh Ellis

Right, because they're class methods on Object that take a param, that's probably why I didn't think to look into how it could work with arrays. Very interesting.