尝试按值而非引用复制对象数组

trying to copy array of objects by value not reference

本文关键字:引用 复制 对象 数组      更新时间:2023-09-26

嗨,我知道以前的帖子已经涵盖了这个主题,但我仍然没有得到我需要的结果。我试图复制一个对象数组,这将是它自己的原始版本,并且在进行更改时不会影响其他对象的数据。到目前为止,当我使用slice((时,复制int数组可以很好地工作,但不适用于对象的矢量。在另一篇文章中提到,对象向量上的slice((仍然会引用对象,所以有没有一种方法可以只通过值来实现???谢谢

property var array: new Array

Rectangle{id: ob1; width:50; height:50; color: "red"; property int num: 1}
Rectangle{id: ob2; width:50; height:50; x: 50; color: "blue"; property int  num: 2}
Rectangle{id: ob3; width:50; height:50; x: 100; color: "green"; property int num: 3}
Component.onCompleted: {
    array.push(ob1)
    array.push(ob2)
    array.push(ob3)
    var array2 = array //slice() will not work here
    array[1].num = 1111  //change made to first array NOT intended for second

    for(var i = 0; i < array.length; i++){
        console.log(array2[i].num)  //print out from second array still shows changes to first...
    }
}

您可以这样做:

var copyOfValues = listOfValues.map(function (value) {
    return $.extend({}, value);
});

您确定array.slice(0(不能工作吗?如果不尝试这个:

var array2 = JSON.parse(JSON.stringify(array));