<分区>
这在逻辑上似乎很明显(字符串不能减),但我想知道在 JavaScript 的底层执行中是如何做出这个决定的。此处究竟如何应用强制规则?
标签 javascript
<分区>
这在逻辑上似乎很明显(字符串不能减),但我想知道在 JavaScript 的底层执行中是如何做出这个决定的。此处究竟如何应用强制规则?
最佳答案
-
is defined in terms of ToNumber
,而 +
有一个额外的 clause for strings (强调我的):
11.6.1 The Addition operator (
+
)The addition operator either performs string concatenation or numeric addition.
The production
AdditiveExpression : AdditiveExpression + MultiplicativeExpression
is evaluated as follows:
- Let
lref
be the result of evaluatingAdditiveExpression
.- Let
lval
beGetValue(lref)
.- Let
rref
be the result of evaluatingMultiplicativeExpression
.- Let
rval
beGetValue(rref)
.- Let
lprim
beToPrimitive(lval)
.- Let
rprim
beToPrimitive(rval)
.- If
Type(lprim)
isString
orType(rprim)
isString
, then
- Return the String that is the result of concatenating
ToString(lprim)
followed byToString(rprim)
[...]
关于javascript - 为什么 1 + '1' = '11' 和 1 - '1' = 0 在 JavaScript(强制转换)中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25893026/