在Javascript中添加和减去字符串和数字 - 自动类型转换? [英] Adding and subtracting strings and numbers in Javascript - auto type conversion?

查看:177
本文介绍了在Javascript中添加和减去字符串和数字 - 自动类型转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们看看下面的Javascript代码。

Let's look at the following Javascript code.

<script type="text/javascript" lang="javascript">
    function test()
    {
        alert('2'+8);
        alert(8-'2');
    }
</script>






在第一个警告框中,它显示结果连接2和8的连接 28 。但是,在第二个警告框中,它会显示两个数字的减法,即 6 。如何?


In the first alert box, it displays the result of concatenation of 2 and 8 which is 28. In the second alert box, however it displays the subtraction of two numbers which is 6. How?

推荐答案

+ 运算符已超载。如果任何操作数是字符串,则执行字符串连接。如果您有两个数字,则执行添加。 - 不会以这种方式重载,并且所有操作数都会转换为数字。

The + operator is overloaded. If any operand is a string, string concatenation is performed. If you have two numbers, addition is performed. The - is not overloaded in such a way and all operands are converted to numbers.

来自规范:


11.6.1加法运算符(+)

(...)

7.如果类型( lprim )是字符串或类型( rprim )是字符串,然后

(...)
7. If Type(lprim) is String or Type(rprim) is String, then


  • 返回串联ToString( lprim )后跟ToString( rprim

  • Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)

8。将添加操作的结果返回到ToNumber( lprim )和ToNumber( rprim )。

(...)

8. Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim).
(...)

11.6.2减法运算符( - )

(...)

5.让 lnum 为ToNumber( lval )。

6.让 rnum 为ToNumber( rval )。

7。将减法运算的结果返回到 lnum rnum

(...)

(...)
5. Let lnum be ToNumber(lval).
6. Let rnum be ToNumber(rval).
7. Return the result of applying the subtraction operation to lnum and rnum.
(...)

这篇关于在Javascript中添加和减去字符串和数字 - 自动类型转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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