The +
操作员没有为数组定义.
发生的事情是 JavaScript将数组转换为字符串并将它们连接起来。
Update
由于这个问题以及我的回答引起了很多关注,我觉得有一个有用且相关的overview关于如何+
操作员的行为也一般。
那么,就这样吧。
排除 E4X 和特定于实现的内容,Javascript(从 ES5 开始)具有6内置数据类型 http://www.ecma-international.org/ecma-262/6.0/#sec-typeof-operator:
- 不明确的
- Null
- Boolean
- Number
- String
- Object
请注意,虽然typeof
有点令人困惑的回报 https://developer.mozilla.org/en/Javascript/Reference/Operators/Special/typeof object
对于空和function
对于可调用对象,Null 实际上不是对象,严格来说,在符合规范的 Javascript 实现中,所有函数都被视为对象。
没错 - Javascript 有没有原始数组像这样;仅称为对象的实例Array
用一些语法糖来减轻痛苦。
包装实体(例如new Number(5)
, new Boolean(true)
and new String("abc")
都是object
类型,而不是人们所期望的数字、布尔值或字符串。然而对于算术运算符Number
and Boolean
表现得像数字一样。
容易吧?完成所有这些后,我们可以继续进行概述。
不同的结果类型+
按操作数类型
|| 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.
Note:正如所指出的CMS https://stackoverflow.com/users/5445/cms,对于某些对象的情况,例如Number
, Boolean
和定制的+
运算符不一定会产生字符串结果。它可能会根据对象到基元转换的实现而有所不同。例如var o = { valueOf:function () { return 4; } };
评估o + 2;
产生6
, a number
, 评估o + '2'
产生'42'
, a string
.
要查看概览表是如何生成的,请访问http://jsfiddle.net/1obxuc7m/ http://jsfiddle.net/1obxuc7m/