简体   繁体   中英

Getting the elements’ indexes when iterating over an array with for-of

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 (ie 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)?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM