Reputation: 4991
2 quick questions
Pseudo code
var arr = [3, 5, 7];
var pos, value;
for (pos in arr) {
console.log(pos); // logs "0", "1", "2"
}
for (value of arr) {
console.log(value); // logs "3", "5", "7"
}
Upvotes: 3
Views: 124
Reputation: 191976
You can get the value in for in simply by using the index on the original array:
var arr = [3, 5, 7];
var pos, value;
for (pos in arr) {
console.log(arr[pos]); // logs 3, 5, 7
}
Note that using for...in to iterate arrays is a bad practice.
Getting the index in for…of
requires an external counter:
var arr = [3, 5, 7];
var pos = 0, value;
for (value of arr) {
console.log(pos++); // logs 0, 1, 2
}
A better solution for both cases would be Array.prototype.forEach
:
arr.forEach((value, index) => {
console.log('index: ', index);
console.log('value: ', value);
});
Upvotes: 4
Reputation: 254926
There is a way:
for (let [key, value] of arr.entries()) {
// ...
}
It uses the Array.prototype.entries()
which returns an iterator over tuples of (key; value)
and array destructuring that turns it into 2 separated variables.
And to address your answer in particular: when you iterate over arrays you should use either for (var i = 0; i < arr.length; ++i)
or for-of
, but not for-in
.
Upvotes: 7
Reputation: 55210
Using for...in
for (pos in arr) {
console.log(arr[pos]);// logs "3", "5", "7"
}
There is no way using for...of
. This will give you an idea.
var arr = ["3", 3, {}, true];
for (value of arr) {
console.log(typeof value);
}
Upvotes: 0