Weird JavaScript operators
I'm having a little problem with an operator. I have a number which is either plussed or subtracted depending on key input. The weird thing is that the operators += 1 and += 11 adds the numbers literally to the static number: 60 becomes 601 and 6011 instead of 61 and 71.
Here is the 开发者_C百科code, so take into consideration that the static number is 60:
switch(e.keyCode) {
case 37:
boxID -= 1;
break;
case 38:
boxID -= 11;
break;
case 39:
boxID += 1; // Becomes 601
break;
case 40:
boxID += 11; // Becomes 6011
break;
}
boxId
is a string in your case. Convert it to a number first using parseInt(boxId)
or just boxId << 0
The reason -=
works is because it only has one function (subtract using Math), so boxId
is cast to a number before the operation. +
is overloaded in JavaScript to mean "string concatenation OR Math addition", so if boxId
is a string, it does string ops.
精彩评论