Vennsoh
Vennsoh

Reputation: 4991

for in and for of loops

2 quick questions

  1. How do I access the index position in an array using for...of?
  2. How do I access the value in an array using for...in?

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

Answers (3)

Ori Drori
Ori Drori

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

zerkms
zerkms

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

codeandcloud
codeandcloud

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

Related Questions