3

In JavaScript, you can iterate over an array with for-of (this is an ES6 feature):

let arr = ['foo', 'bar', 'baz'];

for (let elem of arr) {
  // elem = current element
}

But sometimes, the corresponding element index is also needed in the loop; one approach is to explicitly use the entries iterator like so:

for (let [i, elem] of arr.entries()) {
  // elem = current element
  // i = current index
}

Now, maybe it’s just me, but that .entries() part makes this pattern a bit messy and less readable, so I made entries the default iterator of arr:

arr[Symbol.iterator] = Array.prototype.entries; 

and now I can leave it out:

for (let [i, elem] of arr) {
  // elem = current element
  // i = current index
}

Live demo: https://jsbin.com/gateva/edit?js,console

However, I haven’t figured out how to apply this “hack” to all arrays (i.e. make it the global default). Is that possible and does it have any side effects or downsides (other than having to always specify i, even if you don’t use it, which would be a problem for linters, I guess)?

2
  • If you're worried about linters, jshint supports // jshint esnext: true at the top of the file. Commented May 21, 2016 at 1:29
  • Not certain what requirement is? Commented May 21, 2016 at 1:55

1 Answer 1

2

You can create your own class that extends native Array, and change its default iterator to Array.prototype.entries:

class MyArray extends Array {}
MyArray.prototype[Symbol.iterator] = Array.prototype.entries

Then you create a new instance of MyArray like that:

const arr = new MyArray(1, 2, 3)

And iterate it like that:

for (let [i, elem] of arr) {
  console.log(`Element ${elem} at index ${i}`)
}

See JS Bin demo.

Sign up to request clarification or add additional context in comments.

4 Comments

Note: I thought that changing the default iterator of Array (i.e. Array.prototype[Symbol.iterator] = Array.prototype.entries) would be enough, but there are some weird issues with that. Anyway, modifying native objects is not a good idea.
I’ve tried setting Array.prototype[Symbol.iterator] but I got incorrect output (see the demo in my comment to the other answer).
@ŠimeVidas Yes, that's why you should create your own class.
@Šime You can subclass Array in ES2015, so there's really no longer a reason (if ever) to modify the built-in prototype

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.