【问题标题】:jQuery.extend() deep copy not working as I expected?jQuery.extend() 深拷贝没有像我预期的那样工作?
【发布时间】:2016-12-25 16:46:10
【问题描述】:

我正在使用 jQuery 测试深拷贝,但我得到了一个空对象而不是正确的副本。

但函数loop2 会按预期进行复制(作为参考传递)。

但是loop 不会也获得扩展/合并对象的引用吗?

为什么没有正确通过?

var obj1 = { hello: { f: 1 } };
var obj2 = {};

function loop(original, copy) {
    copy = $.extend(true, {}, original);
    console.log(copy);
}

function loop2(original, copy) {
    $.extend(true, copy, original);
    console.log(copy);
}

function run() {
    loop(obj1, obj2);
    console.log(obj2);

    loop2(obj1, obj2);
    console.log(obj2);
}

输出:

Object {hello: Object}
Object {}  ---> why this one did not get the correct content?
Object {hello: Object}
Object {hello: Object}

【问题讨论】:

    标签: jquery extends


    【解决方案1】:

    这是因为在循环函数中,您正在创建新对象并将其分配给函数范围内的局部变量。全局变量和与之关联的对象不会被修改。此行为未连接到 jQuery.extend(),并且在没有它的情况下也可以正常工作:

    var obj2 = {};
    
    function loop(copy) {
      copy = 'a'; //new value assigned, not its reference
      console.log(copy); //a
    }
    
    loop(obj2);
    console.log('->', obj2); //{}
    //it is OK. Its reference was not touched
    
    function loop2(copy) {
      copy.a = 'a'; //added a new property to its reference
      console.log(copy); //{ a: 'a' }
    }
    
    loop2(obj2);
    console.log('->', obj2); //{ a: 'a' }
    //it is OK. Its reference was touched
    

    【讨论】:

    • 我明白了。但它很奇怪。因为如何创建变量名称与其引用之间的链接?我可以认为如果 var a={test:1},那么“var a”将链接到引用 xyz...所以当在循环函数上时,我将参数副本作为 var a 的引用传递,不管在循环范围内,为副本 arg 分配了一个新引用,因为逻辑会认为它会改变引用,现在 var a 被分配给该新引用
    猜你喜欢
    • 2016-06-19
    • 2013-04-11
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 2023-01-01
    相关资源
    最近更新 更多