Javascript addition and subtraction with a string value

前端 未结 8 1098
猫巷女王i
猫巷女王i 2021-01-20 04:31

I recently went through this typecast JS question:

Given \'11\'+10, the answer is 1110. It is clear that is not 21 because one

8条回答
  •  春和景丽
    2021-01-20 05:02

    I am not an expert on JavaScript, but your question presents a great opportunity to learn from and read through the ECMAScript specification. This is version 5.1, so it will do fine for this question. Section 11.6.2 covers the Subtraction operator:

    The production AdditiveExpression : AdditiveExpression - MultiplicativeExpression is evaluated as follows:

    1. Let lref be the result of evaluating AdditiveExpression.
    2. Let lval be GetValue(lref).
    3. Let rref be the result of evaluating MultiplicativeExpression.
    4. Let rval be GetValue(rref).
    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.

    So, for step 1:

    • Let lref be the result of evaluating AdditiveExpression.

    In your case, that is evaluating '11'. We have lref = '11'.

    • Let lval be GetValue(lref).

    Per line 1 of GetValue (V), if Type(V) is not Reference, return V. Therefore, we return '11'.

    We have lval = '11'.

    • Let rref be the result of evaluating MultiplicativeExpression.

    In your case, that is 10. We have rref = 10.

    • Let rval be GetValue(rref).

    Again, applying line 1 of GetValue (V), if Type(V) is not Reference, return V. Therefore, we return 10.

    We have rval = 10.

    • Let lnum be ToNumber(lval).

    lval = '11'. Calling ToNumber('11') will follow the ToNumber specification for Strings, case 1. There are optional whitespaces surrounding the numeric literal itself. Since your example has no whitespace, the result is simply the numeric literal, which is 11.

    We have lnum = 11.

    • Let rnum be ToNumber(rval).

    rval = 10. Calling ToNumber(10) will follow the ToNumber specification for Number. In that case, the input argument itself is returned, and no conversion occurs. That means we return 10.

    We have rnum = 10.

    • Return the result of applying the subtraction operation to lnum and rnum.

    One more time, per the specification:

    The - operator performs subtraction when applied to two operands of numeric type, producing the difference of its operands; the left operand is the minuend and the right operand is the subtrahend. Given numeric operands a and b, it is always the case that a–b produces the same result as a +(–b).

    We have rnum - lnum = 11 - 10 = 11 + (-10) = 1.

提交回复
热议问题