Home  >  Article  >  Web Front-end  >  Why does JavaScript return \"1,23,4\" when adding arrays with the operator?

Why does JavaScript return \"1,23,4\" when adding arrays with the operator?

DDD
DDDOriginal
2024-10-28 17:20:02549browse

Why does JavaScript return

Why Does JavaScript Return "1,23,4" When Adding Array [1,2] to [3,4]?

When attempting to add elements of two arrays using the operator, unexpected results may arise, as illustrated by the following code snippet:

[1,2] + [3,4]

This expression returns "1,23,4" rather than "[1,2,3,4]".

Understanding the Issue

The operator is not specifically defined for arrays in JavaScript. Instead, when adding arrays, Javascript performs the following steps:

  1. Converts both arrays into strings.
  2. Concatenates the resulting strings, resulting in a comma-separated list of elements.

Fixing the Behavior

To correctly add the elements of two arrays, use the spread operator instead of the operator:

[1,2, ...[3,4]] // [1,2,3,4]

Overview of Operator Behavior

The operator's behavior varies depending on the operand types involved:

Operand Types Result Type
undefined, null, boolean Number
number Number
string String
object String (except for certain objects like Number and Boolean, where the result may vary depending on the implementation)

Refer to the provided table or the referenced jsfiddle for a complete overview of result types across various operand combinations.

The above is the detailed content of Why does JavaScript return \"1,23,4\" when adding arrays with the operator?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn