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

查看:122
本文介绍了在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天全站免登陆