[英]The + + operator in javascript
When I have one plus, I get the wrong answer eg 当我有一个加号,我得到错误的答案,例如
var b = [069];
var total = 0;
total = total + b
console.log(total) // total = 069
However, when I add a second plus so the equation looks like this 但是,当我添加第二个加号时,等式看起来像这样
total = total + + b // total = 69
I get the correct answer of 69. The above is just a simplified example of my issue. 我得到69的正确答案。以上只是我的问题的简化示例。
This works fine, however whilst using JSHint I get a warning saying 这工作正常,但是在使用JSHint时我得到一个警告说
confusing pluses
How can I get the correct answer without using the + + ? 如何在不使用+ +的情况下获得正确的答案? Also, what is this operator called?
此外,这个运营商叫什么?
Javascript unfortunately does a lot of implicit conversions... with your code 不幸的是,Javascript会对您的代码进行大量隐式转换
b + [69]
what happens is that [69]
(an array containing the number 69
) is converted to a string, becoming "69"
. 会发生的是
[69]
(包含数字69
的数组)被转换为字符串,变为"69"
。 This is then concatenated to b
that also is converted in this case to a string "0"
. 然后将其连接到
b
,在这种情况下也将其转换为字符串"0"
。 Thus the result "069"
. 因此结果为
"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
. 但是,如果您在数组前添加另一个一元
+
,则字符串将转换回数字,并且您将数字结果添加到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 +
: 确切的规则非常复杂,但只要考虑二进制
+
的简化形式,您就可以通过Javascript高效工作:
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
. 这意味着单元素数组
[1]
被转换为"1"
......并且暗示了明显的疯狂后果,如[1] == 1
。
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"
将返回"5"
(字符串),其中
+"5"
would return 5
(number). +"5"
将返回5
(数字)。
You could use total = parseInt(total) + parseInt(b);
你可以使用
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. 要获得正确的结果,因为
parseInt()
会尝试从它获得的任何输入参数中生成一个数字。
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
. 理论上,您可以将
total
解析为数字,但是它会容易出现"1" + "0" = "10"
类的错误,从而产生10
,数学上应为1
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.