在javascript中克隆多维数组 [英] Clone Multidimensional Array in javascript

查看:31
本文介绍了在javascript中克隆多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想克隆一个多维数组,这样我就可以在不影响主数组的情况下使用克隆数组.

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

Array.prototype.clone = function () { 
   var newArray = new Array(this.length);
     for(var i=0; i < this.length; i++ ){
        newArray[i] = this[i];
   }
   return newArray;
};

但是问题是因为它使用数组原型,所以它会克隆我的所有数组.所以任何人都可以告诉我这样做的最佳方法是什么.

But problem which is since it is using array prototype so it will clone my all array.so can any body tell me what is the best way of doing this.

推荐答案

需要使用递归

var a = [1,2,[3,4,[5,6]]];

Array.prototype.clone = function() {
    var arr = [];
    for( var i = 0; i < this.length; i++ ) {
//      if( this[i].constructor == this.constructor ) {
        if( this[i].clone ) {
            //recursion
            arr[i] = this[i].clone();
            break;
        }
        arr[i] = this[i];
    }
    return arr;
}

var b = a.clone()

console.log(a);
console.log(b);

b[2][0] = 'a';

console.log(a);
console.log(b);

/*
[1, 2, [3, 4, [5, 6]]]
[1, 2, [3, 4, [5, 6]]]
[1, 2, [3, 4, [5, 6]]]
[1, 2, ["a", 4, [5, 6]]]
*/

原始数组中的任何其他对象将通过引用复制

Any other objects in the original array will be copied by reference though

这篇关于在javascript中克隆多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆