The + + operator in javascript

后端 未结 2 694
逝去的感伤
逝去的感伤 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: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.

提交回复
热议问题