I was playing around with Arrays in jsfiddle and noticed that when I do this:
let a = [0,1,2,3,4];
for (let i in a) {
console.log(a.indexOf(i));
}
it logs:
But when I do:
let a = [0,1,2,3,4];
for (let i in a) {
console.log(a.indexOf(i - 0));
}
it logs:
Minus zero changed the result!
At first I thought it was a jsfiddle problem, but then I tried it with my code editor the same thing happened. Why does this happen can someone explain to me?
When you do:
for (let i in a) ...
This will iterate over indexes of the array as strings. It treats the array like an object and iterates over the indexes like keys. You will get strings: "0", "1"...
You can see that if you print the value and type:
let a = [0,1,2,3,4];
for (let i in a) {
console.log(i, typeof i)
}
Those strings are not in your array — your array has numbers — so findIndex()
doesn't find them and gives you -1
. However when you subtract 0, javascript converts to an integer for you and suddenly it finds them because the indexes match the values.
What you probably want is for...of
to iterate over the values:
let a = [0,1,2,3,4];
for (let i of a) {
console.log("i:", i, typeof i)
console.log("index:", a.indexOf(i));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With