Copy an arbitrary n-dimensional array in JavaScript?

后端 未结 4 1990
余生分开走
余生分开走 2020-12-20 08:32

I am basically looking for a general function copy(array) that will return identical n-dimensional array without any references to the former one.

4条回答
  •  长情又很酷
    2020-12-20 09:00

    I just wanted to add to Paulpro's answer. Note that this is identical to his answer except that I changed copy(new_arr[i]) to copy(arr[i]), and new_arr.length to arr.length.

    function copy(arr){
    var new_arr = arr.slice(0);
    for(var i = arr.length; i--;)
        if(new_arr[i] instanceof Array)
            new_arr[i] = copy(arr[i]);
    return new_arr;
    }
    

    The reason copy(new_arr[i]) worked is because the .slice copied over what arr[i] was pointing at, making them equal.

    Also, while Paulpro's answer works for all cases, if by chance each member of each dimension of the multi-dimensional array is either an array or a non-array you can make it more efficient by only slicing non-array dimensions. I mean what is the point of copying over an array of pointers that will simply be overwritten by the following recursion?

    function copy(arr){
    if(arr[0] instanceof Array){
        var new_arr = new Array(arr.length);
        for(var i = arr.length; i--;)
            new_arr[i] = copy(arr[i]);
    }
    else{var new_arr = arr.slice(0);}
    return new_arr;
    }
    

提交回复
热议问题