javascript - Object.assign() deep copy and shallow copy issues
代言
代言 2017-06-28 09:26:21
0
3
1077

As shown in the picture above, according to the description, Object.assign() is a shallow copy. Why does changing attribute a not point to the same reference, but b.c points to the same reference?

代言
代言

reply all(3)
曾经蜡笔没有小新
var deepCopy = function(src) {
    var ret = {}
    for (var k in src) {
        ret[k] = typeof src[k] ==='object' ? deepCopy(src[k]) : src[k]
    }
    return ret
}

This method has always been used for deep copy. Object.assgin can only deep copy the first layer. Deep copy is still a shallow copy. Just remember this

漂亮男人
let obj3 = Object.assign({},obj1,{b:Object.assign({},obj1.b)});

let obj4 = JSON.parse(JSON.stringify(obj1));
Ty80

Shallow copy: If the attribute element is a complex data type, the inner element copy reference;
slice, concat, jQury’s $.extend({},obj) are all shallow copies;
Click here to learn more

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template