javascript中的+ +运算符 [英] The + + operator in javascript

查看:55
本文介绍了javascript中的+ +运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我有一个加号时,我得到错误的答案,例如。

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, when I add a second plus so the equation looks like this

total = total + + b  // total = 69

我得到69的正确答案。上面只是一个简化的例子我的问题。

I get the correct answer of 69. The above is just a simplified example of my issue.

这很好用,但是在使用JSHint时我得到一个警告说

This works fine, however whilst using JSHint I get a warning saying

confusing pluses

如何在不使用+ +的情况下获得正确答案?此外,这个操作符叫什么?

How can I get the correct answer without using the + + ? Also, what is this operator called?

推荐答案

发表评论作为答案

+ 如果我是正确的话,在变量前会将它强制转换为数字。

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

在你的控制台中试试这个:

Try this in your console:

5将返回5(字符串),其中

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

+5 将返回 5 (数字)。

您可以使用 total = parseInt(total)+ parseInt(b); 来获得正确的结果,如 parseInt()会尝试从它获得的任何输入参数中输出一个数字。

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.

理论上,你可以将总计解析为数字,但它会出现错误,例如1+0=10产生 10 ,数学上应为 1

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.

这篇关于javascript中的+ +运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆