1

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 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;
}
4
  • 1
    how do you define boxID? the javascript runtime thinks it's a string Commented Apr 14, 2011 at 1:55
  • I define boxID like this where the ID is number 60 of the list item: var boxID = $('li.selected').attr('id'); Commented Apr 14, 2011 at 1:57
  • 1
    then follow cwolves advice var boxId = parseInt($("li.selected").attr("id")) Commented Apr 14, 2011 at 1:59
  • 2
    Nitpick: a numeric id is invalid, see w3.org/TR/html401/types.html#type-id Commented Apr 14, 2011 at 6:57

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Remember to use the optional radix parameter and do parseInt(boxId, 10) instead. This prvents "010" from being treated as an octal number.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.