search

Home  >  Q&A  >  body text

javascript - Object.assign() deep copy and shallow copy issues

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?

代言代言2734 days ago1105

reply all(3)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-06-28 09:28:21

    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

    reply
    0
  • 漂亮男人

    漂亮男人2017-06-28 09:28:21

    let obj3 = Object.assign({},obj1,{b:Object.assign({},obj1.b)});
    
    let obj4 = JSON.parse(JSON.stringify(obj1));

    reply
    0
  • PHP中文网

    PHP中文网2017-06-28 09:28:21

    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

    reply
    0
  • Cancelreply