前面的话

"htmlcode">

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
"htmlcode">

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]
 

深拷贝

"htmlcode">

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]


广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!