欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JavaScript数组复制详解

程序员文章站 2022-06-20 22:37:58
前面的话   前面的博文中介绍了对象拷贝,本文将详细介绍数组复制 push function copyarray(arr){...

前面的话

  前面的博文中介绍了对象拷贝,本文将详细介绍数组复制

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
  使用该方法的缺点是数组中的项全部变成了字符串形式

function copyarray(arr){
  var result = [];
  result = arr.join().split(',');
  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]
 

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]
 

深拷贝

  以上方法实现的仅是数组的浅拷贝,如果要实现数组的深拷贝,需要使用递归方法

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]