Fork me on GitHub

JavaScript的深浅拷贝

以下为具体代码:

浅拷贝

// 浅拷贝
var json1 = {
name: 'aaa',
age: 25,
data: {
a: 1,
b: 2
}
};

function copy(parent, child) {
var child = child || {};
for(var i in parent) {
child[i] = parent[i];
}
return child;
}

var json2 = copy(json1);
json2.data.a = 3;
console.log(json1.data.a);// json1.data.a受影响也变成3了
console.log(json2.data.a);

深拷贝

// 深拷贝:利用递归
var json1 = {
name: 'aaa',
age: 25,
data: {
a: 1,
b: 2
}
};

function deepCopy(parent, child) {
var child = child || {};// 并不是直接声明一个新child为空{},传过来的就用传过来的
for(var i in parent) {
if(typeof parent[i] === 'object') {
child[i] = (parent[i].constructor === Array) ? [] : {};// child.data = {};
deepCopy(parent[i], child[i]);// {a: 1,b: 2},传过去的是child.data的空json
}
else {
child[i] = parent[i];// child.data.a ...
}
}
return child;
}

var json2 = deepCopy(json1);
json2.data.a = 3;
console.log(json1.data.a);// json1.data.a不受影响,仍旧是1
console.log(json2.data.a);