Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

Adding and subtracting strings and numbers in Javascript - auto type conversion?

Let's look at the following Javascript code.

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

From the specification:

11.6.1 The Addition operator ( + )

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

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

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

11.6.2 The Subtraction Operator ( - )

(...)
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.
(...)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...