The + + operator in javascript

后端 未结 2 712
逝去的感伤
逝去的感伤 2021-01-23 02:01

When I have one plus, I get the wrong answer e.g.

var b = [069];
var total = 0;

total = total + b
console.log(total) // total = 069

However, w

相关标签:
2条回答
  • 2021-01-23 02:39

    Javascript unfortunately does a lot of implicit conversions... with your code

    b + [69]
    

    what happens is that [69] (an array containing the number 69) is converted to a string, becoming "69". This is then concatenated to b that also is converted in this case to a string "0". Thus the result "069".

    If however you add another unary + in front of the array the string gets converted back to a number and you get a numeric result added to b.

    0 + [69] → 0 + "69" → "0" + "69" → "069"
    0 + + [69] → 0 + + "69" → 0 + 69 → 69
    

    Exact rules are quite complex, but you can be productive with Javascript just considering the simplified form that for binary +:

    • if both are numbers the result is numeric addition
    • otherwise they're converted both to string and result is concatenation

    One thing that is somewhat surprising is that implicit conversion of an array to a string is just the conversion of elements to string adding "," between them as separator.

    This means that the one-element array [1] is converted to "1"... and implies apparently crazy consequences like [1] == 1.

    0 讨论(0)
  • 2021-01-23 02:56

    Posting my comment as an answer

    + in front of a variable would cast it to a number if I'm correct.

    Try this in your console:

    "5" would return "5" (string), where

    +"5" would return 5 (number).

    You could use total = parseInt(total) + parseInt(b); to get a correct result, as parseInt() would try to make a number out of any input parameter it gets.

    Theoritecally, you could just parse the total as a number, but it would be prone to an error like "1" + "0" = "10" resulting in 10, which should mathematically be 1.

    0 讨论(0)
提交回复
热议问题