javascript - 为什么 1 + '1' = '11' 和 1 - '1' = 0 在 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:

  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
    • Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)

[...]

关于javascript - 为什么 1 + '1' = '11' 和 1 - '1' = 0 在 JavaScript(强制转换)中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25893026/

相关文章:

javascript - Angularjs 如何在每个页面显示导航和页脚?

javascript - 在条件语句中检查多个变量为真的有效方法

javascript - 如何从以下 json 数组创建 Backbone 集合?

javascript - 样式化 Polymer Web 组件

javascript - 如何仅在 Blogger 的搜索页面中显示文本?

javascript - event.stopImmediatePropagation();适用于除 Firefox 以外的所有浏览器

javascript - Angular 工厂约定中的一次异步数据加载?

JavaScript 和 DOM 操作(创建和删除)

javascript - API 网关无法启用 CORS

双等号 (==) 和三等号 (===) 之间的 JavaScript 性能差异