SoFunction
Updated on 2025-02-28

Detailed explanation of JavaScript array copy

The previous words

The previous blog post introduces object copying, and this article will introduce array copying in detail

push

function copyArray(arr){
  var result = [];
  for(var i = 0; i < ; i++){
    (arr[i]);
  }
  return result;
}

var obj1=[1,2,3];
var obj2=copyArray(obj1);
(obj1); //[1,2,3]
(obj2); //[1,2,3]
(4);
(obj1); //[1,2,3]
(obj2); //[1,2,3,4]
 

join
The disadvantage of using this method is that all the items in the array have become strings.

function copyArray(arr){
  var result = [];
  result = ().split(',');
  return result;
}

var obj1=[1,2,3];
var obj2=copyArray(obj1);
(obj1); //[1,2,3]
(obj2); //['1','2','3']
(4);
(obj1); //[1,2,3]
(obj2); //['1','2','3',4]
 

concat

function copyArray(arr){
  var result = [];
  result = ();
  return result;
}

var obj1=[1,2,3];
var obj2=copyArray(obj1);
(obj1); //[1,2,3]
(obj2); //[1,2,3]
(4);
(obj1); //[1,2,3]
(obj2); //[1,2,3,4]
 

slice

function copyArray(arr){
  var result = [];
  result = ();
  return result;
}

var obj1=[1,2,3];
var obj2=copyArray(obj1);
(obj1); //[1,2,3]
(obj2); //[1,2,3]
(4);
(obj1); //[1,2,3]
(obj2); //[1,2,3,4]
 

Deep copy

The above method only implements a shallow copy of the array. If you want to implement a deep copy of the array, you need to use a recursive method.

function copyArray(arr,result){
  var result = result || [];
  for(var i = 0; i < ; i++){
    if(arr[i] instanceof Array){
      result[i] = [];
      copyArray(arr[i],result[i]);
    }else{
      result[i] = arr[i];
    }      
  }
  return result;
}

var obj1=[1,2,[3,4]];
var obj2=copyArray(obj1);
(obj1[2]); //[3,4]
(obj2[2]); //[3,4]
obj2[2].push(5);
(obj1[2]); //[3,4]
(obj2[2]); //[3,4,5]