gpt4 book ai didi

javascript - javascript 中的自动转换 : Isn't it supposed to convert a string to a number when done like stringvar = 1+stringvar?

转载 作者:行者123 更新时间:2023-12-03 07:19:28 26 4
gpt4 key购买 nike

(Firefox32,Win 7)

使用便签本时:

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

a = 1 + a - 1;
console.log(a, typeof a);

在控制台中导致:

"02" "string"
101 "number"

我做错了什么吗?

我敢肯定,我经常以这种方式将字符串转换为数字,而且效果很好。 (虽然我更喜欢使用显式转换函数,但由于它如此完美地工作了这么长时间,...:/)

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

最佳答案

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

没有。 :-) 如果任一个 操作数是字符串,则它是字符串连接,而不是加法。这是由 §11.6.1 of the spec 定义的在第 7 步中:

  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. 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). See the Note below 11.6.3.

(我强调“或”)

关于您的第三个示例,1 + a - 1 其中 a"02":

1 + "02" - 1

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

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

+ 是字符串连接,但是由于subtraction operator - 总是 与数字一起使用,它将 "102" 强制转换为 102,然后从中减去 1 得到 101

关于javascript - javascript 中的自动转换 : Isn't it supposed to convert a string to a number when done like stringvar = 1+stringvar?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30128137/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com