为什么学习深拷贝
如何验证深拷贝
原对象和副本对象独立存在,互不影响
如何实现深拷贝
1.只拷贝一维数组
function test2() {
var a = [1, 2, 3];
var b = [];
for (var i = 0; i < a.length; i++) {
b.push(a[i]);
}
console.log(a);
console.log('副本是:' + b);
b[0] = 100;
console.log('修改后的a' + a);
console.log('修改后的b' + b);
}
2.只拷贝对象
function test3() {
var a = {
name: 'cm',
age: 20,
eat: function () {
document.write('曹蒙爱吃肉');
}
};
var b = {};
for (var i in a) {
// document.write(i); //i属性 a[i]
b[i] = a[i];
}
b.name = 'zyp';
console.log(b);
console.log(a);
}
3.拷贝数组嵌套或对象嵌套
function copy(o) {
//1.先判断参数的类型 [] {}
var b = {};
if (Array.isArray(o)) {
b = [];
}
//2.循环参数的每一个元素
for (var i in o) {
//判断参数中每个元素的类型 复杂 基本
if (typeof o[i] === 'object') {
b[i] = copy(o[i]);
} else {
b[i] = o[i];
}
}
return b;
}
var obj = [1, 2, [3, 4], { 'name': 'skq', 'age': 20 }];
var nArray = copy(obj);
console.log(nArray);
相关练习题
function test5() {
var a = [[2, 3], [4, 5, 6], [7, 8], [6, 8]];
var yiwei = []; //一维
var quchong = []; //去重
for (var i = 0; i < a.length; i++) {
for (var j = 0; j < a[i].length; j++) {
yiwei.push(a[i][j]);
}
}
console.log(yiwei);
for (var i = 0; i < yiwei.length; i++) {
if (quchong.indexOf(yiwei[i]) == -1) {
quchong.push(yiwei[i]);
}
}
console.log(quchong);
}
test5();