复制3D阵列

时间:2012-08-14 09:13:57

标签: javascript arrays copy

我有一个3D数组,我想把它的另一个副本放到另一个数组中。

直接分配会将字符串返回到新数组而不是3D数组。

foo = [] //3D array; 
boo = foo //boo becomes a string

知道如何做到这一点吗?

编辑: 这是代码

Background.js

function onRequest(request, sender, sendResponse) {
localStorage = request.mes; // mes is an array
}; 
chrome.extension.onMessage.addListener(onRequest);

2 个答案:

答案 0 :(得分:0)

您可能会使用clone.Try 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 :(得分:0)

我发现的解决方案依赖于使用jQuery,希望这不会成为问题吗?

var a1 = ['test', ['a','b',1], [[1,2,3],[4,5,6]]];
console.log(a1);
var a2 = jQuery.extend(true, {}, a1);
a1[0] = 'test - changed';
console.log(a1);
console.log(a2);

小提琴:http://jsfiddle.net/gRoberts/AhKNx/

只需设置var a2 = a1;即可创建对原始对象的引用,从而导致a2[0]更改为test - changed;

查看你的控制台(Firefox / Chrome中的F12)以查看我小提琴的输出;)

希望有帮助吗?

加文

相关问题