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

http://stackoverflow.com/q/7124884/343194

Problem of 0.

I want to append one array to another, so I write the following code in Firebug:

[1, 2] + [3, 4]Copy the code

But, unexpectedly, it printed:

"1,23,4"Copy the code

Instead of printing what I expected:

[1, 2, 3, 4]Copy the code

What’s going on here? Why does [1,2] + [3,4] not equal [1,2,3,4]?

1. Answer

The + operator in JavaScript serves two purposes:

  1. Add two numbers;

  2. Concatenate two strings.

The specification does not define the behavior of the + operator on arrays, so javascript first converts the array to a string and then performs the + operation on the string.

If you want to concatenate two arrays, you can use the concat method of arrays:

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

Overview of the + operator in javascript

JavaScript has six built-in data types: the data types of the primitive type system. JavaScript actually has two type systems. The first type system was identified by Typeof, called primitive type system, and the second type system was based on it and developed from object type system. The object type system was identified by Instanceof. @ justjavac)

  1. undefined

  2. boolean

  3. number

  4. string

  5. function

  6. object

Note that null and [] are two distinct types, and both return object when typeof is used. But when you use the + operator, it works differently in these two cases.

In JavaScript, an Array is not a primitive type; its existence is nothing more than a sugar-coated syntax; it is actually an instance of the Array class. (ps: function is also the sugar-coated syntax for function instances.)

If you’re still sane, it’s time to spice things up a bit. Javascript object wrapper types such as New Number(5), New Boolean(true), and new String(” ABC “) are also object types; they are not numbers, bools, or strings. However, the arithmetic operators Number and Boolean represent numbers.

Remember what I said earlier about the + operator? It operates on numbers and strings, so Number, Boolean String or Number, Boolean String.

The following table shows the types of results that the + operator produces when it operates on different types



This table works with Chrome 13, Firefox 6, Opera 11 and Internet Explorer 9. Homework assignment: Check other browser compatibility.

Note: the + operation on user-defined objects does not always produce a string result. This depends largely on how the conversion from object type to native type is implemented.

Such as:

var o = { Copy the code

   valueOf : function () { return 4; }

};

Compute o + 2 and you get 6, which is a number; Compute o + ‘2’ to get ’42’, which is a string.

Recommended reading

  • Why does that work? [] concat [1, 2, 3]

  • Why ++[[]][+[]]+[+[]] = 10?

  • Why is math.min () larger than math.max ()? (continue)


Long press the qr code to identify the public number