拷贝简单分为浅拷贝与深度拷贝,即给定一个对象,生成一个相同的对象。
浅拷贝
function copy(source,destiny){
destiny = destiny || {};
if(typeof(source) === 'object'){ // 是object或者array
for(var i in source){
if(source.hasOwnProperty(i)){
destiny[i] = source[i];
}
}
}else{ //string number boolean,undefined null
destiny = source;
}
return destiny;
}
简单测试一下:
var ls = {
a:12,
b:22,
c:{
c1:1,
c2:2
}
};
var ld = copy(ls);
console.log(ld);
结果:
[object Object] {
a: 12,
b: 22,
c: [object Object] {
c1: 1,
c2: 2
}
}
但是,如果改变新生成对象的值,再查看一下source对象
ld.c.c1=3; console.log(ls);
[object Object] {
a: 12,
b: 22,
c: [object Object] {
c1: 3,
c2: 2
}
}
发现source对象也被改变,说明,对于复杂对象(key对应的value值为对象),进行浅拷贝,key对应的使用的是同一个引用,很容易引起问题。
深拷贝
function deepCopy(source,destiny){
destiny = destiny || {};
var i;
for( i in source){
if(source.hasOwnProperty(i)){
if(typeof(source[i]) === "object"){
destiny[i] = Object.prototype.toString.call(source[i]) === "[object Array]" ? [] : {};
deepCopy(source[i],destiny[i]); //递归调用
}else{
destiny[i] = source[i];
}
}
}
return destiny;
}
测试一下:
var s = {
a:1,
b:{
b1:2,
b2:3
},
c:[4,5]
};
var d = deepCopy(s);
[object Object] {
a: 1,
b: [object Object] {
b1: 2,
b2: 3
},
c: [4, 5]
}
d.b.b1=22; console.log(s);
console.log(s)对应的值:
[object Object] {
a: 1,
b: [object Object] {
b1: 2,
b2: 3
},
c: [4, 5]
}
测试地址 : http://jsbin.com/higijadatalu/1/edit
浙公网安备 33010602011771号