Why does [1,2] + [3,4] = “1,23,4” in JavaScript?

本文探讨了JavaScript中加号运算符在不同数据类型间的操作行为,特别是对于数组的操作,揭示了其背后的机制及与其他类型的交互方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I wanted to add the elements of an array into another, so I tried this simple sentence in our beloved Firebug:
[1,2] + [3,4]
It responded with:

"1,23,4"
What is going on?

-----------------------------------------------------


JavaScript has 6 built-in data types:

undefined
boolean
number
string
function
object

Note that neither null nor [] is a separate type - both return object when fed to typeof. However + works differently in either case.

That's right - JavaScript has no primitive arrays as such; only instances of a class called Array with some syntactic sugar to ease the pain.

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.

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 | boolean | number | string | function | object | null | array |
-------------------------------------------------------------------------------------------

undefined | number | number | number | string | string | string | number | string |

boolean | number | number | number | string | string | string | number | string |

number | number | number | number | string | string | string | number | string |

string | string | string | string | string | string | string | string | string |

function | string | string | string | string | string | string | string | string |

object | string | string | string | string | string | string | string | string |

null | number | number | number | string | string | string | number | string |

array | string | string | string | string | string | string | string | string |

-------------------------------------------------------------------------------------------
* this applies to Chrome 13, Firefox 6, Opera 11 and 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. 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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值