Given a for of loop the value of the assigned the variable(i
for this example) is equal to what array[i]
would equal if it was a normal for loop. H
Or
array = ["one", "two", "three"];
for (i = 0, item; item=array[i]; i++) {
console.log(i); // Logs the current index number;
console.log(item); // Logs the current item in the array;
}
You can use the entries function. It will return a index/value pair for each entry in the array like:
[0, "one"]
[1, "two"]
[2, "three"]
Use this in tandem with array destructuring to resolve each entry to the appropriate variable name:
const arr = ["one", "two", "three"]
for(const [index, value] of arr.entries()) {
console.log(index, value);
}
Babel REPL Example
You can use the entries() function to get an iterator that includes the indices.
for (let [index, value] of [1, 2, 3].entries())
console.log(index + ':' + value);
or, if you dont like the let [,]
notation:
for (let entry of [1, 2, 3].entries())
console.log(entry[0]+ ':' + entry[1]);
But what about other array-likes? Well, you could easily just take care of it yourself, really
let index = 0;
for (let ch of 'abcd') {
++index;
//your code
}
Or, you can pretty easily patch in your own implementation
Object.defineProperty(String.prototype, 'indexerator', {get:function() {
var elements = this[Symbol.iterator]();
var index = 0;
var output;
return {
[Symbol.iterator] : function() { return this; },
next : function() {
if (!(output = elements.next()).done)
output.value = [index++, output.value];
return output;
}
};
}});
/*other code*/
for (let [index, ch] of 'abcd'.indexerator)
console.log(index + ':' + ch);
demonstrations
nothing simple ... if you want "simple access" to both the item and the index in a loop over an array, use forEach
e.g.
array.forEach(function(item, index) {
...
});
or as T.J. Crowder pointer out (and I missed the ES6 tag)
array.forEach((item, index) => {
...
});
like many programming languages, javascript has multiple ways to do similar things, the skill is in choosing the right tool for the job
use indexOf
to get the index back
let array = ["one", "two", "three"];
for (let i of array) {
console.log(i);
console.log(array.indexOf(i));
}
NOTE: will only work for a array with no duplicates.
You mean this?
array = ["one", "two", "three"];
for (i = 0; i < array.length; i++) {
console.log(i); // Logs the current index number;
console.log(array[i]); // Logs the index matching in the array;
}
Also a good comment from Kaiido was that you can use this to get the value from the array directly as a variable.
for (var ind = 0, i=array[ind]; ind < array.length; i=array[++ind]) {
console.log(i);
console.log(ind);
}