Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript中的加号运算符趣事 #19

Open
zhaoqize opened this issue Feb 5, 2018 · 0 comments
Open

JavaScript中的加号运算符趣事 #19

zhaoqize opened this issue Feb 5, 2018 · 0 comments
Labels

Comments

@zhaoqize
Copy link
Owner

zhaoqize commented Feb 5, 2018

加号运算符(+)在JavaScript中无处不再,但是就是因为它太常用以至于我们忽略了它。

加号运算符的两种含义

  • 用在数字上,就是相加
  • 用在字符串上,就是连接

这个应该很简单,我们来试试

数字相加

var a = 3;
var b = 6;
var c = a + b; //=> 9

字符串相加

var a = 3;
var b = '6';
var c = a + b; //=> '36'

这个结果理所应当,但是不是我们想要的。
这里的+号被解释成了连接符号。我们只需要这样即可:c = a + b*1,这样就解释成了运算符加号

连接与运算的优先级

这个问题不可避免,在我们开发中经常遇到。
先来看看下面这个例子:

var money1 = 2000;
var money2 = 3000;
var total = '2个月一共存了' + money1 + money2 + '元' ; 

我想这个结果应该可以预料到: 2个月一共存了20003000元
要是现实中真是这样运算,我们岂不是发了。
出现这种情况的原因是:

  • '2个月一共存了' 遇到 money1 时,处理成了'2个月一共存了2000'
  • '2个月一共存了2000' 遇到 money2时,处理成了 '2个月一共存了20003000'
  • ...

结论是:连接比相加优先级高

我们这个问题解决起来也很简单: var total = '2个月一共存了' + (money1 + money2) + '元' ; 通过括弧改变运算优先级。

@zhaoqize zhaoqize added the Tip label Feb 20, 2018
@zhaoqize zhaoqize added JS Tip and removed Tip labels Aug 7, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant