Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 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 OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...