Home  >  Article  >  Web Front-end  >  Detailed explanation of JavaScript array copy

Detailed explanation of JavaScript array copy

高洛峰
高洛峰Original
2017-02-03 13:38:001623browse

Previous words

Object copy was introduced in the previous blog post. This article will introduce array copy in detail

push

function copyArray(arr){
  var result = [];
  for(var i = 0; i < arr.length; i++){
    result.push(arr[i]);
  }
  return result;
}
 
var obj1=[1,2,3];
var obj2=copyArray(obj1);
console.log(obj1); //[1,2,3]
console.log(obj2); //[1,2,3]
obj2.push(4);
console.log(obj1); //[1,2,3]
console.log(obj2); //[1,2,3,4]

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

function copyArray(arr){
  var result = [];
  result = arr.join().split(&#39;,&#39;);
  return result;
}
 
var obj1=[1,2,3];
var obj2=copyArray(obj1);
console.log(obj1); //[1,2,3]
console.log(obj2); //[&#39;1&#39;,&#39;2&#39;,&#39;3&#39;]
obj2.push(4);
console.log(obj1); //[1,2,3]
console.log(obj2); //[&#39;1&#39;,&#39;2&#39;,&#39;3&#39;,4]

concat

function copyArray(arr){
  var result = [];
  result = arr.concat();
  return result;
}
 
var obj1=[1,2,3];
var obj2=copyArray(obj1);
console.log(obj1); //[1,2,3]
console.log(obj2); //[1,2,3]
obj2.push(4);
console.log(obj1); //[1,2,3]
console.log(obj2); //[1,2,3,4]

slice

function copyArray(arr){
  var result = [];
  result = arr.slice();
  return result;
}
 
var obj1=[1,2,3];
var obj2=copyArray(obj1);
console.log(obj1); //[1,2,3]
console.log(obj2); //[1,2,3]
obj2.push(4);
console.log(obj1); //[1,2,3]
console.log(obj2); //[1,2,3,4]

deep copy

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

function copyArray(arr,result){
  var result = result || [];
  for(var i = 0; i < arr.length; 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);
console.log(obj1[2]); //[3,4]
console.log(obj2[2]); //[3,4]
obj2[2].push(5);
console.log(obj1[2]); //[3,4]
console.log(obj2[2]); //[3,4,5]

For more detailed articles on JavaScript array copy, please pay attention to 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