0

I have this piece of code,

let array = ["cj1rdd9fc00013f69ccln57g0", "cj1rdda8x00023f69g9281ay8"];
for (let [key, value] of array) {
  console.log(key, value);
}
I expect, 0 cj1rdd9fc00013f69ccln57g0 and 1 cj1rdda8x00023f69g9281ay8 as the output. what am I missing here? How can I get the desired output?
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
Aki
  • 179
  • 2
  • 14
  • What are you getting? Some errors or current results would help please. – Chris Watts Apr 21 '17 at 05:18
  • @ChrisWatts OP expects `key` to be indexes and `value` to be element of array – Rajesh Apr 21 '17 at 05:19
  • Refer https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of – Jitendra Khatri Apr 21 '17 at 05:20
  • I found that adding array.entries() in the loop body makes it work fine. – Aki Apr 21 '17 at 05:22
  • @AkhileshBhushan, see [my answer](http://stackoverflow.com/a/43534850/2545680) for in-depth explanation. – Max Koretskyi Apr 21 '17 at 05:52
  • Don't put answers in the questions. Instead, accept the correct answer. –  Apr 21 '17 at 05:55
  • Read the [documentation](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of), where `for...of` is described with perfect clarity. –  Apr 21 '17 at 05:57
  • @torazaburo, it's missing some in-depth details though, for example, two iterators I mentioned in [my answer](http://stackoverflow.com/a/43534850/2545680) – Max Koretskyi Apr 21 '17 at 06:09

6 Answers6

4

Here is a bit of under the hood explanation.

for..of loop works on iterables. On each iteration it calls iterator.next().value to get values. Standard Array implementation has two kinds of iterators - the one that returns only values and the other that returns [key, value] pairs. If you need to get the second type of iterator, use array.entries().

let array = ["cj1rdd9fc00013f69ccln57g0", "cj1rdda8x00023f69g9281ay8"];
for (let [key, value] of array.entries()) {
  console.log(key, value);
}

Here is the demo of two types of iterators:

var arr = ['a','b'];
var valueIterator = arr[Symbol.iterator]();
valueIterator.next().value; // returns a
valueIterator.next().value; // returns b

var arr = ['a','b'];
var valueKeyIterator = arr.entries();
valueKeyIterator.next().value; // returns [0, a]
valueKeyIterator.next().value; // returns [1, b]
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
2

Let try to understand whats happening here:

As per MDN-Docs, for..of provides value of each iteration to the assignment.

So when you do for(var v of array), v will hold value.

Now when you do let [key, value], you are using something thats called as Destructuring Assignment.

What it does is, for given list of variables, it will assign values at corresponding index value.

So, in let [a,b] = [10, 20], a=10 and b=20.

Coming back to your example,

let [key, value] of array,

is evaluated as let [key, value] = "cj1rdd9fc00013f69ccln57g0", so key holds value at 0th index, a.k.a c and value holds j.


How can I get the desired output

You can use other looping mechanisms like for, array.forEach etc.

There are other mechanisms like .map, .filter, .some, .every, .reduce but they have their own usecase, and can be suggested based on the processing logic.

Array.forEach

let array = ["cj1rdd9fc00013f69ccln57g0", "cj1rdda8x00023f69g9281ay8"];

array.forEach(function(value, index){
  console.log(index, value)
})
Community
  • 1
  • 1
Rajesh
  • 24,354
  • 5
  • 48
  • 79
  • Thank you so much for the explanation, well my use case was not that simple, as I had to use async and await in the loop. – Aki Apr 21 '17 at 05:40
  • I know that. Hence have mentioned other options. Read about them and choose based on your requirement. Also do check their browser compatibility. – Rajesh Apr 21 '17 at 05:42
  • I have edited my query with the answer and actual async function, thank you. – Aki Apr 21 '17 at 05:47
  • @Rajesh, you may find [my answer](http://stackoverflow.com/a/43534850/2545680) interesting – Max Koretskyi Apr 21 '17 at 06:07
0

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of

The way for of works is each time it will grab just the value, not the index.

let array = ["cj1rdd9fc00013f69ccln57g0", "cj1rdda8x00023f69g9281ay8"];
for (let item of array) {
  console.log(item);
}

If you want to include the index, see this question:

How do you get the loop counter/index using a for-in syntax in JavaScript?

Community
  • 1
  • 1
ハセン
  • 377
  • 3
  • 5
0

This Code, Console.log Array

 let array = ["cj1rdd9fc00013f69ccln57g0", "cj1rdda8x00023f69g9281ay8"];
 var i,j,tempstring;
    for (i=0,j=array.length; i<j; i++) {
        tempstring = array[i];
        console.log(tempstring);
    }
Saeed Heidarizarei
  • 8,406
  • 21
  • 60
  • 103
0

This is a destructuring assignment . This will work for es6 Maps and not for Arrays . For arrays you can just use a for of loop .

Balaji V
  • 918
  • 3
  • 10
  • 28
-1

If you want to get the value and index of an array in every iteration using some fancy iteration, try this.

let array = ["cj1rdd9fc00013f69ccln57g0", "cj1rdda8x00023f69g9281ay8"];
array.map((value, index) => {
    console.log(index, key);
});
Kashif Nazar
  • 20,775
  • 5
  • 29
  • 46
  • 1
    `array.map` without return statement and assignment is just **bad** coding. You are wasting a feature. Use `.forEach` instead – Rajesh Apr 21 '17 at 05:43
  • I would respectfully disagree. Even in strong typed languages such as Java, you are not bound to use a value returned by a function. – Kashif Nazar Apr 21 '17 at 10:11
  • 1
    I'm sorry if I was not clear enough. Every function has its own purpose. `Array.map` maps certain property or mutates value of every iteration. But if you are not returning value, it will return `undefined` manually. Then you are not assigning it to something, but `.map` will return an array created internally with undefined values. So you are asking engine to do extra work for no reason. Using `.forEach` is the right approach here. – Rajesh Apr 21 '17 at 10:15
  • It also reduces the readability of code as `.map` is expected to return something and final value is assigned to something, but you are doing none and adds a gap in understanding. – Rajesh Apr 21 '17 at 10:17
  • I agree, now :) Thanks – Kashif Nazar Apr 21 '17 at 11:20