为什么JavaScript中的[1,2] + [3,4] =“1,23,4”?

本文翻译自:Why is [1,2] + [3,4] = “1,23,4” in JavaScript?

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? 到底是怎么回事?


#1楼

参考:https://stackoom.com/question/TtVU/为什么JavaScript中的


#2楼

Another result using just a simple "+" sign will be: 使用简单的“+”符号的另一个结果将是:

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

So something like this should work (but!): 所以这样的事情应该有效(但是!):

var a=[1,2];
var b=[3,4];
a=a+','+b; // [1,2,3,4]

... but it will convert the variable a from an Array to String! ...但它会将变量a从Array转换为String! Keep it in mind. 记在心上。


#3楼

Some answers here have explained how the unexpected undesired output ( '1,23,4' ) happens and some have explained how to obtain what they assume to be the expected desired output ( [1,2,3,4] ), ie array concatenation. 这里的一些答案已经解释了意外的不良输出( '1,23,4' )是如何发生的,有些已经解释了如何获得他们认为是预期的期望输出( [1,2,3,4] ),即数组级联。 However, the nature of the expected desired output is actually somewhat ambiguous because the original question simply states "I wanted to add the elements of an array into another...". 然而,预期的期望输出的性质实际上有些模棱两可,因为原始问题只是说“我想将数组的元素添加到另一个......”。 That could mean array concatenation but it could also mean tuple addition (eg here and here ), ie adding the scalar values of elements in one array to the scalar values of the corresponding elements in the second, eg combining [1,2] and [3,4] to obtain [4,6] . 可能意味着阵列串联,但它可能意味着元组除了(例如这里在这里 ),即在所述第二添加元素的标量值在一个阵列中的相应元素的标量值,例如结合[1,2][3,4] [4,6] [3,4]获得[4,6]

Assuming both arrays have the same arity/length, here is one simple solution: 假设两个阵列具有相同的arity / length,这是一个简单的解决方案:

 const arr1 = [1, 2]; const arr2 = [3, 4]; const add = (a1, a2) => a1.map((e, i) => e + a2[i]); console.log(add(arr1, arr2)); // ==> [4, 6] 


#4楼

It adds the two arrays as if they were strings . 它将两个数组添加为字符串

The string representation for the first array would be "1,2" and the second would be "3,4" . 第一个数组的字符串表示形式为“1,2” ,第二个数组的字符串表示形式为“3,4” So when the + sign is found, it cannot sum arrays and then concatenate them as being strings. 因此,当找到+符号时,它不能对数组求和,然后将它们连接为字符串。


#5楼

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. 你在一起添加的是数组引用(JS转换为字符串),而不是看起来像数字。 It's a bit like adding strings together: "hello " + "world" = "hello world" 这有点像添加字符串: "hello " + "world" = "hello world"


#6楼

The + operator is not defined for arrays . 没有为数组定义 +运算符。

What happens is that Javascript converts arrays into strings and 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 overview about how the + operator behaves in general also. 由于这个问题,因此我的答案得到了很多关注,我觉得有一个关于+运算符一般行为的概述是有用和相关的。

So, here it goes. 所以,在这里。

Excluding E4X and implementation-specific stuff, Javascript (as of ES5) has 6 built-in data types : 排除E4X和特定于实现的东西,Javascript(从ES5开始)有6种内置数据类型

  1. Undefined 未定义
  2. Null 空值
  3. Boolean 布尔
  4. Number
  5. String
  6. Object 宾语

Note that although typeof somewhat confusingly returns object 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. 请注意,虽然typeof 有点令人困惑地返回 Null的object和可调用对象的function ,但Null实际上不是Object,严格来说,在符合规范的Javascript实现中,所有函数都被认为是对象。

That's right - Javascript has no primitive arrays as such; 那是对的 - Javascript 没有原始数组 ; only instances of an Object called Array with some syntactic sugar to ease the pain. 只有一个名为Array的Object的实例,带有一些语法糖,以减轻痛苦。

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. 添加更多的混淆,包装实体,如new Number(5)new Boolean(true)new String("abc")都是object类型,而不是人们可能期望的数字,布尔值或字符串。 Nevertheless for arithmetic operators Number and Boolean behave as numbers. 然而,对于算术运算符, NumberBoolean表现为数字。

Easy, huh? 好吗,对吧? With all that out of the way, we can move on to the overview itself. 完成所有这些后,我们可以继续进行概述。

Different result types of + by operand types + by操作数类型的不同结果类型

            || 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. *适用于Chrome13,FF6,Opera11和IE9。 Checking other browsers and versions is left as an exercise for the reader. 检查其他浏览器和版本是留给读者的练习。

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. 注意:正如CMS所指出的,对于某些对象(如NumberBoolean和自定义对象), +运算符不一定会产生字符串结果。 It can vary depending on the implementation of object to primitive conversion. 它可以根据对象到原始转换的实现而变化。 For example var o = { valueOf:function () { return 4; } }; 例如var o = { valueOf:function () { return 4; } }; var o = { valueOf:function () { return 4; } }; evaluating o + 2; 评估o + 2; produces 6 , a number , evaluating o + '2' produces '42' , a string . 产生6 ,一个number ,评估o + '2'产生'42' ,一个string

To see how the overview table was generated visit http://jsfiddle.net/1obxuc7m/ 要查看概述表的生成方式,请访问http://jsfiddle.net/1obxuc7m/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值