Making an independent copy of a reversed array in JavaScript

前端 未结 5 1704
故里飘歌
故里飘歌 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:14
    function reverseArr(input) {
        return input.slice().reverse();
    }
    
    0 讨论(0)
  • 2021-01-15 16:17

    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;
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-15 16:30

    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

    0 讨论(0)
  • 2021-01-15 16:34

    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.

    0 讨论(0)
提交回复
热议问题