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.
/** map data we are interested in looping */ let map = { '0': [], '1': ['1'] }
below are the different scenarios and there respective output.
/** * Method 1: Trouble maker * * details: * when debugged it picks up 1 and then jumps to 0 before going inside * the loop for printing console */ for(let val in map['1']){ console.log(val); // gives 0 } /** Method 2: using forEach but i cant use return */ map['1'].forEach((pre) => { console.log(pre); // gives 1 }) /** Method 3: this is more verbose but can always fallback */ let result = map['1']; for(let i=0; i< result.length; i++){ console.log(result[i]); // gives 1 }
Advertisement
Answer
Your for...in
loop is wrong. val
should be the index of the array, so index 0 would be 1
.
Example:
let map = { '0': [], '1': ['1'] } const array = map['1']; for(let index in array){ console.log(array[index]); // gives 1 }