为什么 [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
Why is [1,2] + [3,4] = "1,23,4" in JavaScript?
提问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 种内置数据类型:
- Undefined
- Null
- Boolean
- Number
- String
- Object
- 不明确的
- 空值
- 布尔值
- 数字
- 细绳
- 目的
Note that although typeof
somewhat confusingly returnsobject
for Null and function
for 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 实现中,所有函数都被视为对象。object
function
That's right - Javascript has no primitive arraysas such; only instances of an Object called Array
with 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 object
type, not numbers, booleans or strings as one might expect. Nevertheless for arithmetic operators Number
and Boolean
behave 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
, Boolean
and 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 .concat
methodinstead:
如果要连接两个数组以生成一个新数组,请改用以下.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 + 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)
- Return the result of applying the addition operation to
ToNumber(lprim)
andToNumber(rprim)
. See the Note below 11.6.3.
11.6.1 加法运算符 ( + )
加法运算符执行字符串连接或数字加法。生产
AdditiveExpression : AdditiveExpression + MultiplicativeExpression
评估如下:
- 让
lref
成为评估的结果AdditiveExpression
。- 我们
lval
是GetValue(lref)
。- 让
rref
成为评估的结果MultiplicativeExpression
。- 我们
rval
是GetValue(rref)
。- 我们
lprim
是ToPrimitive(lval)
。- 我们
rprim
是ToPrimitive(rval)
。- 如果
Type(lprim)
是String
或者Type(rprim)
是String
,那么
- 返回作为连接结果的字符串,
ToString(lprim)
后跟ToString(rprim)
- 返回应用加法运算的结果
ToNumber(lprim)
和ToNumber(rprim)
。请参阅下面的注释 11.6.3。
You can see that each operand is converted ToPrimitive
. By reading further we can find that ToPrimitive
will 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.
这是因为, + 运算符假定操作数是字符串,如果它们不是数字。因此,如果它不是数字,它首先将它们转换为字符串并连接以给出最终结果。此外,它不支持数组。