JavaScript中的自动转换:完成后,是否应该将字符串转换为数字,例如stringvar = 1 + stringvar? [英] Autoconversion in javascript: Isn't it supposed to convert a string to a number when done like stringvar = 1+stringvar?

查看:106
本文介绍了JavaScript中的自动转换:完成后,是否应该将字符串转换为数字,例如stringvar = 1 + stringvar?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(Firefox32,Win 7)

(Firefox32, Win 7)

使用便签本时:

var a = "2";
console.log('a',a);
a = 1-1 + a;
console.log('a',a);
a = 1 + a -1;
console.log('a',a);

在控制台中导致:

"a" "2"
"a" "02"
"a" 101

我做错什么了吗?

我敢肯定,我经常将字符串转换为数字,并且可以正常工作. (尽管我更喜欢使用显式转换功能,但是由于它在如此长的时间内运行得如此完美,...:/)

I'm sure I have converted strings to numbers that way very often, and it worked. (Though I like to use the explicit converting functions much more, but as it worked so flawlessly for so long, ... :/ )

为什么第三行是数字?但是不是第二个吗?为什么是101?

And why is the third line a number? But not the second? And why is it 101?

推荐答案

不是应该像stringvar = 1 + stringvar这样将字符串转换为数字吗?

Isn't it supposed to convert a string to a number when done like stringvar = 1+stringvar?

不. :-)如果其中一个操作数是字符串,则为字符串连接,而不是加法.由规范的§11.6.1定义在步骤7中:

Nope. :-) If either operand is a string, it's string concatenation, not addition. This is defined by §11.6.1 of the spec in Step 7:

  1. 让lref成为评估AdditiveExpression的结果.
  2. 让lval为GetValue(lref).
  3. 让rref成为对MultiplicativeExpression求值的结果.
  4. 让rval为GetValue(rref).
  5. 让lprim设为ToPrimitive(lval).
  6. 让rprim成为ToPrimitive(rval).
  7. 如果Type(lprim)是String ,则Type(rprim)是String,则
  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 lprim be ToPrimitive(lval).
  6. Let rprim be ToPrimitive(rval).
  7. If Type(lprim) is String or Type(rprim) is String, then
  1. 返回由ToString(lprim)和ToString(rprim)串联而成的字符串

  • 返回对ToNumber(lprim)和ToNumber(rprim)应用加法运算的结果.请参阅下面的注释11.6.3.
  • Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim). See the Note below 11.6.3.
  • (我强调或")

    第三个示例1 + a - 1,其中a"02":

    1 + "02" - 1
    

    加法(binary +)和减法(binary -)运算符具有相同的优先级,并且它们都是从左到右的关联,因此执行如下操作:

    The addition (binary +) and subtraction (binary -) operators have the same precedence and both are left-to-right associative, so that's performed like this:

    (1 + "02") - 1    =>    "102" - 1    => 101
    

    +是字符串连接,但是由于减法运算符- 始终与数字一起使用,它在将"102"减去1以获得101之前将"102"强制为102.

    The + is string concatenation, but since the subtraction operator - always works with numbers, it coerces the "102" to 102 before subtracting 1 from it to get 101.

    这篇关于JavaScript中的自动转换:完成后,是否应该将字符串转换为数字,例如stringvar = 1 + stringvar?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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