JavaScript 数组 + 数组 = 字符串?

标签 javascript arrays

当您尝试在 JavaScript 中将一个数组添加到另一个数组时,它会将其转换为字符串。通常,当以另一种语言执行此操作时,会将列表组合起来。

JavaScript

[1, 2] + [3, 4] = "1,23,4"

Python

[1, 2] + [3, 4] = [1, 2, 3, 4]

我并不是想引发一场关于哪种语言更好的争论。但 JavaScript 对我来说毫无意义。 JavaScript 这样做有逻辑原因吗?或者这只是语言的一个怪癖?

最佳答案

This is how the Addition Operator (+) is defined..

+ 运算符对于其他值类型(如数组)没有“特殊含义/重载”,并且 ECMAScript 中的行为独立于任何其他值类型的行为。其他语言。

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)
  8. Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim). See the Note below 11.6.3.

这种情况下的转换相当微妙,但它是数组值的结果,是没有相应基元类型的对象,由于 [ToPrimitive] 操作而调用了“toString” 。因此,规则应用大致如下。

   [1,2] + [3,4]
-> [1,2].toString() + [3,4].toString()     // Rules #5 and #6
-> "1,2" + "3,4"                           // Rule #7
-> "1,23,4"

关于JavaScript 数组 + 数组 = 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23450642/

相关文章:

arrays - 数组中数组的和

javascript - if 语句中的不同字符串

javascript - jQuery 文档处理程序窃取输入字段中的按键

javascript - 如何使用 javascript 或 jQuery 使用标签内已知的 html 内容查找标签的 ID?

javascript - react 中的排序表。只有一列有效时怎么可能?

javascript - 如何检查元素在 AngularJS 模板上是否可见?

c - 动态长度数组

javascript - 当我从下拉列表中选择一个选项时,jQuery typeahead 停止工作

c - 制作一个程序来实现与数组一起使用的函数

c - 在 char[][] 和 char** 中访问成员的区别