Clone Multidimensional Array in javascript

后端 未结 3 1039
名媛妹妹
名媛妹妹 2020-12-10 20:37

I want to make a clone of multidimensional Array so that i can play arround with the clone array without affecting main Array.

I\'m using following function to do so

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-10 21:13

    vsync is correct, my first answer doesn't handle var a = [[1,2],[3,4]];
    So here's an improved version

    var a = [[1,2],[3,4]];
    Array.prototype.clone = function() {
        var arr = this.slice(0);
        for( var i = 0; i < this.length; i++ ) {
            if( this[i].clone ) {
                //recursion
                arr[i] = this[i].clone();
            }
        }
        return arr;
    }
    
    var b = a.clone()
    
    console.log(a);
    console.log(b);
    
    b[1][0] = 'a';
    
    console.log(a);
    console.log(b);
    
    //[[1, 2], [3, 4]]
    //[[1, 2], [3, 4]]
    //[[1, 2], [3, 4]]
    //[[1, 2], ["a", 4]]
    

提交回复
热议问题