当您尝试在 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:
- 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 Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
- 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/