Making an independent copy of a reversed array in JavaScript

杀马特。学长 韩版系。学妹 提交于 2019-12-01 10:34:39

You are making a new independent array, but you are not making independent copies of the items that fill your arrays. You need to do something like:

function reverseArr(input) {
    var ret = new Array;
    for(var i = input.length-1; i >= 0; i--) {
        ret.push({
            positionx: input[i].positionx, 
            positiony: input[i].positiony, 
            index: input[i].index
        });
    }

    return ret;
}

so that you are generating new objects (with the same properties) as well as the new array.

cgnorthcutt

All you have to do is clone your array before you reverse it! :)

The shortest way to type is:

var b = a.slice();

But using concat is correct as well. See:

Javascript fastest way to duplicate an Array - slice vs for loop

If slice does not create a copy for you, you can use numpy arrays and create a deep copy this way:

np.copy(a);

see: http://docs.scipy.org/doc/numpy/reference/generated/numpy.copy.html

use this function

function reverseArray(input) {
var newArray = new Array();
for(var i = input.length-1; i >= 0; i--) {
    newArray.push(input[i]);
   }
   return newArray;
}
function reverseArr(input) {
    return input.slice().reverse();
}

Your function is working correctly, even if it could be abbreviated to

return input.slice().reverse();

//This will show that pointOrigins2 is not an independent copy of pointOrigins1
//When pointOrigins2 is modified pointOrigins1 is also being modified
pointOrigins2[0].index++;

No. You are not modifying the pointOrigins2 array here, you are only accessing it and modifying the point object - the same point that was in the pointOrigins1 array. Yet, pointOrigins1 !== pointOrigins2.

You can modify the array independent from the other, e.g. like

pointOrigins2[0] = {
    positionx: pointOrigins2[0].positionx, 
    positiony: pointOrigins2[0].positiony, 
    index:     pointOrigins2[0].index + 1
};

and pointOrigins1 will stay untouched. So if you want to have points whose properties you can modify without being reflected somewhere else, you will need to create new points.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!