As the existing answer pointed out there is a index argument passed to the array iteration callbacks callback(item, idx, array)
Iterators
However you could also use an iterator
[Array.values()][1]
returns an array iterator. You use iterator.next()
to step over the items, and iterator.next().value
to get an item.
That way you do not need an index and can use the more performant for of
loop that does not have a ready idx.
const iterator = input.values(); for (const obj of stored) { obj.value = iterator.next().value }
However is works equally well in an array iteration function
const iterator = input.values(); stored.forEach(obj => obj.value = iterator.next().value)
Via a generator
You can also create a custom iterator using a generator function. For example say you wanted to reverse the input order.
function *reversed(array) { // NOTE the * signifies this is a generator var i = array.length; while (i--) { yield array[i] } } var iterator = reversed(input); // create reverse iterator of input for (const obj of stored) { obj.value = iterator.next().value } // or iterator = reversed(input); // restart reverse iterator of input stored.forEach(obj => obj.value = iterator.next().value);
Note that the iteration assigning to store
remained unchanged from above examples.
count
variable to increment the index,Array.forEach
accepts a second ( optional ) parameter which is the current index that you can use :stored.forEach((obj, ndx) => { obj.value = input[ndx]; });
jsfiddle.net/qm6yep5r\$\endgroup\$