Reputation: 10564
I'm writing in JavaScript and detected this strange behavior that I can't explain.
for (i in bubbles){
bubbles[i].string = "some stuff!" // <- no errors here
results[0] = i - 1
results[1] = i + 1
results[2] = parseInt(i) + 1
}
when i = 1
this happens
results[0] -> 0
results[1] -> 11
results[2] -> 2
is this even possible?! Maybe it's due to other errors in the code. I tried to isolate the case above but, if you need it, here's the whole code
for (i in bubbles){
if (bubbles[i].check()){
// define which boubble has been clicked and start dragging
bubbleDrag[2] = bubbles[i].check();
bubbleDrag[1] = i;
bubbleDrag[0] = true;
// define where to check to avoid overlapping dates
if (i != 0 && i < bubbles.length - 1){
bubbleDrag[3] = i - 1;
bubbleDrag[4] = i + 1;
} else if (i == 0 && bubbles.lenght > 1){
bubbleDrag[3] = i + 1;
} else if (i == bubbles.lenght - 1){
bubbleDrag[3] = i - 1;
}
}
}
Upvotes: 0
Views: 185
Reputation: 7898
Javascript is interpreting your code.
results[0] = i - 1
// string minus number, so javascript "assumes" you want "i" as a number
results[1] = i + 1
// string concatenate with a number, so javascript assumes you want a concatenated string
More examples.
"30" - 10; // echoes number 20
"30" + 10; // echoes string "3010"
Some people like that languages interpret like this, some don't. I find myself in the latter. IMO, string + number should throw an error since intentions aren't explicit. Loose/non-strict interpretations may end up leading to unexpected results. If you read some of Douglas Crockford's code, you'll notice he uses extensively strict type comparison (===, !==) and this is part of the reason why.
Upvotes: 1