Making an independent copy of a reversed array in JavaScript

前端 未结 5 1735
故里飘歌
故里飘歌 2021-01-15 15:50

Here is my fiddle: http://jsfiddle.net/sepoto/Zgu9J/1/

I\'m starting with a reverse function:

function reverseArr(input) {
    var ret = new Array;
          


        
5条回答
  •  深忆病人
    2021-01-15 16:20

    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.

提交回复
热议问题