添加和减去数字作为字符串 [英] Adding and Subtracting Numbers as Strings

查看:225
本文介绍了添加和减去数字作为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在关于SO的问题上阅读了以下内容:

I read the following on a question on SO:


'7'+ 4给出'74',而'7' - 4在JavaScript中给出3

'7' + 4 gives '74', whereas '7' - 4 gives 3 in JavaScript

为什么会发生这种情况?

Why does this happen?

推荐答案

'+'运算符是为字符串和数字定义的,所以当你将它应用于字符串和数字时,数字将被转换为字符串,然后字符串将被连接:
'7'+ 4 =>'7'+'4'=>'74'
但' - '仅针对数字而非字符串定义,因此字符串'7'将转换为数字:
'7' - 4 => 7 - 4 => 3

The '+' operator is defined for both strings and numbers, so when you apply it to a string and a number, the number will be converted so string, then the strings will be concatenated: '7' + 4 => '7' + '4' => '74' But '-' is only defined for numbers, not strings, so the string '7' will be converted to number: '7' - 4 => 7 - 4 => 3

这篇关于添加和减去数字作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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