JavaScript学习笔记——浅拷贝、深拷贝
参考自:http://www.cnblogs.com/yichengbo/archive/2014/07/10/3835882.html
一、数组的深浅拷贝
在使用JavaScript对数组进行操作的时候,我们经常需要将数组进行备份,事实证明如果只是简单的将它赋予其他变量,那么我们只要更改其中的任何一个,然后其他的也会跟着改变,这就导致了问题的发生。
var arr01 = ["One","Two","Three"]; var arrt02 = arr01; arrt02[1] = "test"; console.log("arr01:" + arr01); //One,test,Three console.log("arr02:" + arrt02); //One,test,Three
像上面的这种直接赋值的方式就是浅拷贝,很多时候,这样并不是我们想要得到的结果,其实我们想要的是arr的值不变。
方法一:js的slice方法
var arr01 = ["One","Two","Three"]; var arrt02 = arr01.slice(0); arrt02[1] = "test"; console.log("arr01:" + arr01); //One,Two,Three console.log("arr02:" + arrt02); //One,test,Three
方法二:js的concat方法
var arr01 = ["One","Two","Three"]; var arrt02 = arr01.concat(); arrt02[1] = "test"; console.log("arr01:" + arr01); //One,Two,Three console.log("arr02:" + arrt02); //One,test,Three
二、对象的深拷贝
var a={name:'yy',age:26}; var b={}; b = deepCopy(a); b.name = 'zz'; console.log(b); //Object { name="zz", age=26} console.log(a); //Object { name="yy", age=26} //定义对象的深拷贝方法 function deepCopy(obj) { var result={}; for (var k in obj) { result[k] = obj[k] instanceof Object ? deepCopy(obj[k]) : obj[k]; } return result; }
三、兼容数组和对象深拷贝的综合方法
var snail01 = { name:'奔跑的蜗牛', age:'26', like:{ fruit:'orange', sport:'football' } } // 创建深拷贝方法 function deepCopy(obj){ var result,b; //result:存储拷贝数据,b:存储是否为数组的布尔值 b = obj instanceof Array; if(obj instanceof Array || obj instanceof Object){ result = b ? [] : {}; for(var k in obj){ if(obj[k] instanceof Array || obj[k] instanceof Object){ result[k] = deepCopy(obj[k]); }else{ result[k] = obj[k]; } } } return result; } var snail02 = deepCopy(snail01); snail02.name = 'running snail02'; snail02.like.fruit = 'banana'; console.log(snail02); // Object { name="running snail02", age="26", like=Object { fruit="banana", sport="football"}} console.log(snail01); // Object { name="奔跑的蜗牛", age="26", like=Object { fruit="orange", sport="football"}}