3

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"
}
naveen
  • 53,448
  • 46
  • 161
  • 251
Vennsoh
  • 4,853
  • 5
  • 26
  • 41

3 Answers3

7

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
zerkms
  • 249,484
  • 69
  • 436
  • 539
4

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);
});
Community
  • 1
  • 1
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

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);
}
naveen
  • 53,448
  • 46
  • 161
  • 251