I am surprised i have not faced this until today, but this costed me a whole day as I blindly believed my for...in
will work as it should. Please help me understand why this happens with for...in
? Now i’m paranoid to use for...in
.
I have simplified the example so that we can just focus on the root cause.
JavaScript
x
6
1
/** map data we are interested in looping */
2
let map = {
3
'0': [],
4
'1': ['1']
5
}
6
below are the different scenarios and there respective output.
JavaScript
1
21
21
1
/**
2
* Method 1: Trouble maker
3
*
4
* details:
5
* when debugged it picks up 1 and then jumps to 0 before going inside
6
* the loop for printing console */
7
for(let val in map['1']){
8
console.log(val); // gives 0
9
}
10
11
/** Method 2: using forEach but i cant use return */
12
map['1'].forEach((pre) => {
13
console.log(pre); // gives 1
14
})
15
16
/** Method 3: this is more verbose but can always fallback */
17
let result = map['1'];
18
for(let i=0; i< result.length; i++){
19
console.log(result[i]); // gives 1
20
}
21
Advertisement
Answer
Your for...in
loop is wrong. val
should be the index of the array, so index 0 would be 1
.
Example:
JavaScript
1
10
10
1
let map = {
2
'0': [],
3
'1': ['1']
4
}
5
6
const array = map['1'];
7
8
for(let index in array){
9
console.log(array[index]); // gives 1
10
}