Home > Web Front-end > JS Tutorial > body text

Detailed explanation of JavaScript array copy

高洛峰
Release: 2017-02-03 13:38:00
Original
1636 people have browsed it

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]
Copy after login

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]
Copy after login

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]
Copy after login

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]
Copy after login

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]
Copy after login

For more detailed articles on JavaScript array copy, please pay attention to 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!