We know that the concat method can combine two or more arrays to create a new array. In fact, the concat method can also be used to copy arrays. In this article, we will introduce the use of the concat method to copy arrays in How to copy an array using concat method in JavaScript.
When we need to copy an array, we may think of the following methods
Code
var arr1 = [1,2,3,4,5]; var arr2 = []; arr2 = arr1; console.log(arr1); console.log(arr2);
The execution results are as follows:
[1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
In this example, array arr1 is assigned to another array arr2.
Looking at the execution results, it seems that the contents of the array are copied and the same array is created.
However, since an array is a "reference type" of data, it does not copy the value, but simply shares the location of the memory where the value is stored.
Therefore, we write the following code
arr2.push(6); console.log(arr1); console.log(arr2);
The execution results are as follows
[1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6]
According to the above results, we can find that even if we only add a new value 6 to arr2, the array arr1 A 6 will also be added to . This is because both
arrays only refer to the location where the value is stored. If you change the data in either array, both will change.
So let’s use the concat method to copy the array
Let’s look at a specific example
var arr1 = [1,2,3,4,5]; var arr2 = []; arr2 = arr1.concat(); arr2.push(6); console.log(arr1); console.log(arr2);
The execution results are as follows
[1, 2, 3, 4, 5] [1, 2, 3, 4, 5, 6]
To copy another array To copy an array to array arr2, you only need to execute concat() in the copy source arr1.
This article ends here. For more exciting content, you can pay attention to the relevant column tutorials on the PHP Chinese website! ! !
The above is the detailed content of How to copy an array using concat method in JavaScript. For more information, please follow other related articles on the PHP Chinese website!