主页 > 前端 > javascript >
来源:未知 时间:2017-02-06 09:24 作者:xxadmin 阅读:次
[导读] 前面的话 前面的博文中介绍了对象拷贝,本文将详细介绍数组复制 push functioncopyArray(arr){varresult=[];for(vari=0;iarr.length;i++){result.push(arr[i]);}returnresult;}varobj1=[1,2,3];varobj2=copyArray(obj1);c...
前面的话 前面的博文中介绍了对象拷贝,本文将详细介绍数组复制 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] |
自学PHP网专注网站建设学习,PHP程序学习,平面设计学习,以及操作系统学习
京ICP备14009008号-1@版权所有www.zixuephp.com
网站声明:本站所有视频,教程都由网友上传,站长收集和分享给大家学习使用,如由牵扯版权问题请联系站长邮箱904561283@qq.com