【问题标题】:Assign array of object content to a new array [duplicate]将对象内容数组分配给新数组[重复]
【发布时间】:2016-10-22 08:29:48
【问题描述】:

我正在尝试将一个对象数组分配给另一个数组,但是当我创建新数组并在其他函数中更改其值时,原始数组也会更改(这不好)。我可以用另一种方式吗? 这是一个例子:http://codepen.io/Xiwi/pen/rLMbYp

【问题讨论】:

    标签: javascript arrays object concat


    【解决方案1】:

    看起来您需要复制/克隆数组,这样它就不会被引用更改。

    如果数组中只有 Primitive Types,你可以这样做:

    var test3 = JSON.parse(JSON.stringify(test2));
    

    否则,您需要递归解决方案并在您的问题中更具体。

    例子:

    var test1 = [{name: 'test1'}];
    var test2 = [{name: 'test2'}];
    var test3 = JSON.parse(JSON.stringify(test2));
    
    test3[0].name = 'test3';
    
    // Open console
    console.log('Test2: ',test2[0]); // Object {name: "test2"}
    console.log('Test3: ',test3[0]); // Object {name: "test3"}

    【讨论】:

    • 你不用序列化,相信[].splice(0,0, arr);会做原语的拷贝
    • 对不起[].concat(arr)
    • @kirinthos 没有。像这样你会遇到同样的问题。在这里查看:jsfiddle.net/jbL0vm9m
    • 呃,我说的是基元数组
    • @kirinthos,如果你的意思是基元数组,那么你可以像这样使用var test3 = test2.slice();jsfiddle.net/jbL0vm9m/1
    【解决方案2】:

    对象本质上是引用。您必须创建一个新对象并分配另一个对象的值:

    var test3 = [ Object.assign({}, test2[0]) ];
    

    【讨论】:

      【解决方案3】:

      使用简单的.map 将一个对象数组复制到另一个对象。

      var test1 = [{name: 'test1'}];
      var test2 = [{name: 'test2'}];
      //var test3 = test2.slice(0); //doesn't work. objects are still references
      var test3 = test2.map(function(obj){
        //return obj; //doesn't work. objects are still references
        var o={}; //create brand new object
        for(var prop in obj)
          o[prop]=obj[prop];//assign properties
        return  o;//works
      });
      
      test3[0].name = 'test3';
      
      // Open console
      console.log('Test2: ',test2[0]);
      console.log('Test3: ',test3[0]);
      

      【讨论】:

        猜你喜欢
        • 2016-02-03
        • 2011-10-27
        • 1970-01-01
        • 2019-12-06
        • 2010-11-22
        • 2017-12-10
        • 1970-01-01
        • 1970-01-01
        • 2013-02-22
        相关资源
        最近更新 更多