网络编程 
首页 > 网络编程 > 浏览文章

JavaScript数组复制详解

(编辑:jimmy 日期: 2024/11/18 浏览:3 次 )

前面的话

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


上一篇:理解javascript中的Function.prototype.bind的方法
下一篇:windows 下安装nodejs 环境变量设置
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网 网站地图 SiteMap