JavaScript中的自动转换:完成后,是否应该将字符串转换为数字,例如stringvar = 1 + stringvar? [英] Autoconversion in javascript: Isn't it supposed to convert a string to a number when done like 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:
- 让lref成为评估AdditiveExpression的结果.
- 让lval为GetValue(lref).
- 让rref成为对MultiplicativeExpression求值的结果.
- 让rval为GetValue(rref).
- 让lprim设为ToPrimitive(lval).
- 让rprim成为ToPrimitive(rval).
- 如果Type(lprim)是String 或 ,则Type(rprim)是String,则
- Let lref be the result of evaluating AdditiveExpression.
- Let lval be GetValue(lref).
- Let rref be the result of evaluating MultiplicativeExpression.
- Let rval be GetValue(rref).
- Let lprim be ToPrimitive(lval).
- Let rprim be ToPrimitive(rval).
- If Type(lprim) is String or Type(rprim) is String, then
- 返回由ToString(lprim)和ToString(rprim)串联而成的字符串
(我强调或")
第三个示例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屋!