深拷贝/浅拷贝之Js / AngularJs

时间:2022-06-16 15:20:24
var a = [1,2,3,4];
var b = a;
b[1] = 8;
console.log("a:" + a );//1,8,3,4
consloe.log("b:" + b);//1,8,3,4

上面的这种直接赋值的方式其实就是浅拷贝,但是上面打印的并我们想要得到的结果,其实我们想要的是a的值不变。所以这就需要用其他方式来解决

关于JS 的深拷贝:

数组深拷贝:

(1),slice

var a = [1,2,3,4];
var b = a.slice(0);
b[1] = 8;
console.log("a:" + a );//1,2,3,4
consloe.log("b:" + b);//1,8,3,4

(2),concat

var a = [1,2,3,4];
var b = a.concat();//连接一个空的
b[1] = 8;
console.log("a:" + a );//1,2,3,4
consloe.log("b:" + b);//1,8,3,4

对象深拷贝:

对象的深拷贝,就只能遍历整个对象,赋值给新的对象

var deep_copy= function(obj) { //对象深拷贝
var new_obj={};
for (var key in obj) {
new_obj[key] = typeof obj[key]===’object’? deep_copy(obj[key]): obj[key];//递归赋值
}
return new_obj;
}

关于AngularJs 的浅拷贝:

<div ng-app>
<div ng-controller="demoCtrl">
{{sample}}
</div>
</div>
function demoCtrl($scope){
var DeepCopy = function(data) {
angular.forEach(arguments, function(obj) {//遍历arguments-->即data
if (obj !== data) {
angular.forEach(obj, function(value, key) {
if(angular.isObject(data[key]) || angular.isArray(data[key])){
DeepCopy(data[key], value);
} else {
data[key] = angular.copy(value);
}
});
}
});
return data;
}; $scope.a = {
"one":11,"two":[
{
"name":"小明",
"age":13,
"items":[
{
"a":1,
"b":1,
"c":2
}
]
},
{
"age":24,
"items":[
{
"a":10,
"c":10
}
]
}
]
};
var b = {
"one":33, "two":[
{
"age":63,
"items":[
{
"a":88,
"b":88
}
]},
{
"age":14,
"items":[
{
"a":70,
"b":70
}
]
}
]
};
DeepCopy($scope.a,b);
}

结果:

{"one":33,"two":[{"name":"小明","age":63,"items":[{"a":88,"b":88,"c":2}]},{"age":14,"items":[{"a":70,"c":10,"b":70}]}]}

这样的对象深拷贝才满足要求,完美复制!