Home >Web Front-end >JS Tutorial >Concatenate arrays using concat function in JavaScript

Concatenate arrays using concat function in JavaScript

WBOY
WBOYOriginal
2023-11-18 17:35:171445browse

Concatenate arrays using concat function in JavaScript

In JavaScript, merging arrays is a common operation and can be implemented using the concat function. The concat function can combine multiple arrays into a new array. Let's look at a specific code example.

First, we define several arrays as sample data:

var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
var arr3 = [7, 8, 9];

Next, use the concat function to merge these three arrays into a new array:

var newArr = arr1.concat(arr2, arr3);

Run After completing this code, newArr will become a new array containing all elements, whose contents are [1, 2, 3, 4, 5, 6, 7, 8, 9].

You can also pass in any number of arrays for merging in the function call. For example, we can define another array arr4:

var arr4 = ["a", "b", "c"];

We merge arr4 with the previous newArr:

var finalArr = newArr.concat(arr4);

After running this code, finalArr will contain all previous arrays and arr4 Element whose content is [1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c"].

It should be noted that the concat function does not change the original array, but creates a new array and returns it. Therefore, the values ​​of the original array will not change.

In addition, the concat function can also be used to merge multi-dimensional arrays. Consider the following two-dimensional array:

var matrix1 = [[1, 2], [3, 4]];
var matrix2 = [[5, 6], [7, 8]];

We can use the concat function to merge matrix1 and matrix2 into a new two-dimensional array:

var newMatrix = matrix1.concat(matrix2);

The merged newMatrix will become an array containing two A new two-dimensional array whose contents are [[1, 2], [3, 4], [5, 6], [7, 8]].

Through the above example code, we can see that using the concat function can easily merge arrays, whether they are one-dimensional arrays or multi-dimensional arrays. This is very useful when working with array data. Hope this little code example helps!

The above is the detailed content of Concatenate arrays using concat function in JavaScript. 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