# javascript 数组的深度复制

1. 数组的简单复制

1.1 简单遍历

function array_copy(arr) {
var out = [], i, len;
if (out[i] instanceof Array === false){
return arr;
}

for (i = 0, len = arr.length; i < len; i++) {
if (out[i] instanceof Array){
out[i] = deepcopy(arr[i]);
} else {
out[i] = arr[i];
}
};
return a;


}

//测试
var arr1 = [1, 2, 3, 4],
arr2 = array_copy(arr1);

console.log(arr1, arr2);
arr2[2] = 10;
console.log(arr1[2], arr2[2]);

1.2 变通的复制实现

var arr1 = [1, 2, 3, 4],
arr2 = arr1.slice(0),
arr3 = arr1.concat();

console.log(arr1, arr2, arr3);
arr2[2] = 10;
arr3[2] = 11;
console.log(arr1[2], arr2[2], arr3[2]);

1. 数组的深度复制

2.1 使用 JSON 方法

JSON.stringify(array) 然后再 JSON.parse()。示例：

var arr1 = [1, 2, [3, 4], {a: 5, b: 6}, 7],
arr2 = JSON.parse(JSON.stringify(arr1));

console.log(arr1, arr2);
arr2[1] = 10;
arr2[3].a = 20;
console.log(arr1[1], arr2[1]);
console.log(arr1[3], arr2[3]);

https://github.com/douglascrockford/JSON-js/blob/master/json2.js

2.2 深度复制的完全实现

Object.prototype.clone = function () {
var o = {};
for (var i in this) {
o[i] = this[i];
}
return o;
};
Array.prototype.clone = function () {
var arr = [];
for (var i = 0; i < this.length; i++)
if (typeof this[i] !== ‘object’) {
arr.push(this[i]);
} else {
arr.push(this[i].clone());
}
return arr;
};

//测试1 Object
var obj1 = {
name: ‘Rattz’,
age: 20,
hello: function () {
return “I’m ” + name;
}
};
var obj2 = obj1.clone();
obj2.age++;
console.log(obj1.age);

//测试2 Array
var fun = function(log) {console.log},
arr1 = [1, 2, [3, 4], {a: 5, b: 6}, fun],
arr2 = arr1.clone();

console.log(arr1, arr2);

arr2[2][1]= ‘Mike’;
arr2[3].a = 50;
arr2[4] = 10;
console.log(arr1, arr2);

2.3 使用 jQuery 的 extend 方法

var arr1 = [1, 2, [3, 4], {a: 5, b: 6}, 7],
arr2 = \$.extend(true, [], arr1);

console.log(arr1, arr2);
arr2[1] = 10;
console.log(arr1, arr2);

#### javaScript中对象的深度克隆

2016-09-21 21:19:44

#### JS数组的深浅拷贝

2017-07-08 11:39:02

#### Js 深度复制数组

2014-12-11 14:45:56

#### js实现深度拷贝

2017-10-29 21:32:34

#### JavaScript深度克隆（深度拷贝）一个对象

2014-09-15 09:22:42

#### js--引用类型Array--3.数组简单复制和深度复制

2017-02-23 18:33:23

#### toString()和深浅拷贝

2007-08-07 21:03:00

#### 数组深度复制

2017-11-22 15:30:42

#### java List 深度复制方法

2015-05-25 16:17:20

#### JS对象深度克隆实现

2016-10-07 16:11:42