Home > Web Front-end > JS Tutorial > How to copy an array using concat method in JavaScript

How to copy an array using concat method in JavaScript

不言
Release: 2019-01-19 16:48:43
Original
3919 people have browsed it

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.

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);
Copy after login

The execution results are as follows:

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
Copy after login

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);
Copy after login

The execution results are as follows

[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
Copy after login

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);
Copy after login

The execution results are as follows

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template