为什么 [1,2] + [3,4] = "1,23,4" 在 JavaScript 中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7124884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:56:54  来源:igfitidea点击:

Why is [1,2] + [3,4] = "1,23,4" in JavaScript?

javascriptarraysstringconcatenation

提问by okeen

I wanted to add the elements of an array into another, so I tried this:

我想将一个数组的元素添加到另一个数组中,所以我尝试了这个:

[1,2] + [3,4]

It responded with:

它的回应是:

"1,23,4"

What is going on?

到底是怎么回事?

回答by Saul

The +operator is not defined for arrays.

+操作者没有为数组定义

What happens is that Javascript converts arrays into stringsand concatenates those.

发生的事情是 Javascript将数组转换为字符串并将它们连接起来。

 

 

Update

更新

Since this question and consequently my answer is getting a lot of attention I felt it would be useful and relevant to have an overviewabout how the +operator behaves in general also.

由于这个问题以及因此我的回答受到了很多关注,我认为对操作员的一般行为进行概述也是有用和相关的+

So, here it goes.

所以,它来了。

Excluding E4X and implementation-specific stuff, Javascript (as of ES5) has 6built-in data types:

排除 E4X 和特定于实现的东西,Javascript(从 ES5 开始)有6 种内置数据类型

  1. Undefined
  2. Null
  3. Boolean
  4. Number
  5. String
  6. Object
  1. 不明确的
  2. 空值
  3. 布尔值
  4. 数字
  5. 细绳
  6. 目的

Note that although typeofsomewhat confusingly returnsobjectfor Null and functionfor callable Objects, Null is actually not an Object and strictly speaking, in specification-conforming Javascript implementations all functions are considered to be Objects.

请注意,尽管Null 和可调用对象的typeof返回有些令人困惑,但Null 实际上不是对象,严格来说,在符合规范的 Javascript 实现中,所有函数都被视为对象。objectfunction

That's right - Javascript has no primitive arraysas such; only instances of an Object called Arraywith some syntactic sugar to ease the pain.

没错 - Javascript没有原始数组;只有Array使用一些语法糖调用的对象实例才能减轻痛苦。

Adding more to the confusion, wrapper entities such as new Number(5), new Boolean(true)and new String("abc")are all of objecttype, not numbers, booleans or strings as one might expect. Nevertheless for arithmetic operators Numberand Booleanbehave as numbers.

更令人困惑的是,诸如new Number(5),new Boolean(true)new String("abc")object类的包装实体都是类型,而不是人们所期望的数字、布尔值或字符串。尽管如此,对于算术运算符Number,其Boolean行为与数字相同。

Easy, huh? With all that out of the way, we can move on to the overview itself.

容易吧?有了所有这些,我们可以继续进行概述本身。

Different result types of +by operand types

+按操作数类型的不同结果类型

            || undefined | null   | boolean | number | string | object |
=========================================================================
 undefined  || number    | number | number  | number | string | string | 
 null       || number    | number | number  | number | string | string | 
 boolean    || number    | number | number  | number | string | string | 
 number     || number    | number | number  | number | string | string | 
 string     || string    | string | string  | string | string | string | 
 object     || string    | string | string  | string | string | string | 

* applies to Chrome13, FF6, Opera11 and IE9. Checking other browsers and versions is left as an exercise for the reader.

* 适用于 Chrome13、FF6、Opera11 和 IE9。检查其他浏览器和版本留给读者作为练习。

Note:As pointed out by CMS, for certain cases of objects such as Number, Booleanand custom ones the +operator doesn't necessarily produce a string result. It can vary depending on the implementation of object to primitive conversion. For example var o = { valueOf:function () { return 4; } };evaluating o + 2;produces 6, a number, evaluating o + '2'produces '42', a string.

注意:正如CMS所指出的,对于对象的某些情况,例如Number,Boolean和自定义对象,+运算符不一定会产生字符串结果。它可以根据对象到原始转换的实现而变化。例如var o = { valueOf:function () { return 4; } };评估o + 2;产生6,a number,评估o + '2'产生'42',a string

To see how the overview table was generated visit http://jsfiddle.net/1obxuc7m/

要查看概览表是如何生成的,请访问http://jsfiddle.net/1obxuc7m/

回答by Facebook Staff are Complicit

JavaScript's +operator has two purposes: adding two numbers, or joining two strings. It doesn't have a specific behaviour for arrays, so it's converting them to strings and then joining them.

JavaScript 的+运算符有两个目的:将两个数字相加,或者连接两个字符串。它对数组没有特定的行为,因此它将它们转换为字符串,然后加入它们。

If you want to join two arrays to produce a new one, use the .concatmethodinstead:

如果要连接两个数组以生成一个新数组,请改用以下.concat方法

[1, 2].concat([3, 4]) // [1, 2, 3, 4]

If you want to efficiently add all elements from one array to another, you need to use the .push method:

如果要有效地将一个数组中的所有元素添加到另一个数组,则需要使用.push 方法

var data = [1, 2];

// ES6+:
data.push(...[3, 4]);
// or legacy:
Array.prototype.push.apply(data, [3, 4]);

// data is now [1, 2, 3, 4]

The behaviour of the +operator is defined in ECMA-262 5e Section 11.6.1:

+运算符的行为在ECMA-262 5e 第 11.6.1 节中定义:

11.6.1 The Addition operator ( + )

The addition operator either performs string concatenation or numeric addition. The production AdditiveExpression : AdditiveExpression + MultiplicativeExpressionis evaluated as follows:

  1. Let lrefbe the result of evaluating AdditiveExpression.
  2. Let lvalbe GetValue(lref).
  3. Let rrefbe the result of evaluating MultiplicativeExpression.
  4. Let rvalbe GetValue(rref).
  5. Let lprimbe ToPrimitive(lval).
  6. Let rprimbe ToPrimitive(rval).
  7. If Type(lprim)is Stringor Type(rprim)is String, then
    1. 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.

11.6.1 加法运算符 ( + )

加法运算符执行字符串连接或数字加法。生产AdditiveExpression : AdditiveExpression + MultiplicativeExpression评估如下:

  1. lref成为评估的结果AdditiveExpression
  2. 我们lvalGetValue(lref)
  3. rref成为评估的结果MultiplicativeExpression
  4. 我们rvalGetValue(rref)
  5. 我们lprimToPrimitive(lval)
  6. 我们rprimToPrimitive(rval)
  7. 如果Type(lprim)String或者Type(rprim)String,那么
    1. 返回作为连接结果的字符串,ToString(lprim)后跟ToString(rprim)
  8. 返回应用加法运算的结果ToNumber(lprim)ToNumber(rprim)。请参阅下面的注释 11.6.3。

You can see that each operand is converted ToPrimitive. By reading further we can find that ToPrimitivewill always convert arrays to strings, producing this result.

你可以看到每个操作数都被转换了ToPrimitive。通过进一步阅读我们可以发现,ToPrimitive总是将数组转换为字符串,从而产生这样的结果。

回答by Doug

It adds the two arraysas if they were strings.

它将两个数组相加,就好像它们是字符串一样

The string representation for the first array would be "1,2"and the second would be "3,4". So when the +sign is found, it cannot sum arrays and then concatenate them as being strings.

第一个数组的字符串表示是"1,2",第二个是"3,4"。因此,当+找到符号时,它不能对数组求和,然后将它们连接为字符串。

回答by Rocket Hazmat

The +concats strings, so it converts the arrays to strings.

+concats字符串,因此它的数组转换为字符串。

[1,2] + [3,4]
'1,2' + '3,4'
1,23,4

To combine arrays, use concat.

要组合数组,请使用concat.

[1,2].concat([3,4])
[1,2,3,4]

回答by maerics

In JavaScript, the binary addition operator (+) performs both numerical addition and string concatenation. However, when it's first argument is neither a number nor a string then it converts it into a string (hence "1,2") then it does the same with the second "3,4" and concatenates them to "1,23,4".

在 JavaScript 中,二元加法运算符 ( +) 执行数字加法和字符串连接。但是,当它的第一个参数既不是数字也不是字符串时,它会将其转换为字符串(因此是“ 1,2”),然后它对第二个“ 3,4”执行相同操作并将它们连接到“ 1,23,4”。

Try using the "concat" method of Arrays instead:

尝试使用数组的“concat”方法:

var a = [1, 2];
var b = [3, 4];
a.concat(b) ; // => [1, 2, 3, 4];

回答by tadman

It's converting the individual arrays to strings, then combining the strings.

它将单个数组转换为字符串,然后组合字符串。

回答by user286806

[1,2]+[3,4]in JavaScript is same as evaluating:

[1,2]+[3,4]在 JavaScript 中与评估相同:

new Array( [1,2] ).toString() + new Array( [3,4] ).toString();

and so to solve your problem, best thing would be to add two arrays in-place or without creating a new array:

因此要解决您的问题,最好的办法是就地添加两个数组或不创建新数组:

var a=[1,2];
var b=[3,4];
a.push.apply(a, b);

回答by Adam Fabicki

It looks like JavaScript is turning your arrays into strings and joining them together. If you want to add tuples together, you'll have to use a loop or a map function.

看起来 JavaScript 正在将您的数组转换为字符串并将它们连接在一起。如果要将元组添加在一起,则必须使用循环或映射函数。

回答by Jamie Dixon

It's doing exactly what you asked it to do.

它正在做你要求它做的事情。

What you're adding together are array references (which JS converts to strings), not numbers as it seems. It's a bit like adding strings together: "hello " + "world"= "hello world"

您加在一起的是数组引用(JS 将其转换为字符串),而不是看起来的数字。有点像把字符串加在一起:"hello " + "world"="hello world"

回答by Prashant Singh

It is because, + operator assumes that the operands are string, if they are not numbers. So, it first converts them to string and concats to give the final result , if its not a number. Also, it does not support arrays.

这是因为, + 运算符假定操作数是字符串,如果它们不是数字。因此,如果它不是数字,它首先将它们转换为字符串并连接以给出最终结果。此外,它不支持数组。