Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript minus zero changes results

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:

-1, -1, -1, -1, -1

But when I do:

let a = [0,1,2,3,4];

for (let i in a) {
    console.log(a.indexOf(i - 0));
}

it logs:

0,1,2,3,4

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?

like image 598
JoeTheHobo Avatar asked Dec 23 '22 20:12

JoeTheHobo


1 Answers

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));
}
like image 96
Mark Avatar answered Dec 28 '22 23:12

Mark