2014-10-07 57 views
1

我的意思是動態維數組是可以有多種維度的多維數組。我需要創建一個函數對多維數組的元素進行操作,而不管它們的尺寸如何。我寫了一個函數,它應該遍歷多維數組的所有元素,但我找不到獲取它們的方法。這是我寫的:JavaScript中有動態維數組嗎?

function loopThrough (multiArray, dimensions) { 

    var i, indexes = new Array(dimensions.length); 
    // stores the current position in multiArray as index combination 

    for (i in indexes) indexes[i] = 0; // position is initialised with [0, 0, ... 0] 

    while (i >= 0) { 

    doStuff(multiArray[indexes[0], indexes[1], ... indexes[?]]); // this is where I got stuck 

    for (i = indexes.length - 1; i >= 0 && ++indexes[i] >= dimensions[i]; indexes[i--] = 0); 
    // creates the next index combination 

    } 

} 

我也需要一種方法來創建這樣的數組。說,在一個對象的構造函數,如:

function MultiArray (dimensions) { 

    this.array = []; 

    // create multidimensional array 

} 

例如,如果我想創建一個5x3x8數組,我應該能夠調用MultiArray([5,3,8]);只是與調用MultiArray([4,6]);一個4x6的陣列,或MultiArray([7]);對於一個普通的7長陣列。

+0

dimentions的例子嗎? – juvian 2014-10-07 20:55:35

+1

你必須使用遞歸 – hindmost 2014-10-07 21:04:41

+0

@最後你沒有_have to_,但那是_one way_。 – Mathletics 2014-10-07 22:06:42

回答

0
function MultiArray(dimensions) { 
    this.elements = []; 
    var leaf = dimensions.length == 1; 
    var dimension = dimensions.shift(); 
    for (var i = 0; i < dimension; ++i) { 
     this.elements.push(leaf ? undefined : new MultiArray(dimensions)); 
    } 
} 

MultiArray.prototype.get(indexes) { 
    var leaf = indexes.length == 1; 
    var index = indexes.shift(); 
    return leaf ? this.elements[index] : this.elements[index].get(indexes); 
} 

MultiArray.prototype.set(indexes, value) { 
    var leaf = indexes.length == 1; 
    var index = indexes.shift(); 
    if (leaf) { 
     this.elements[index] = value; 
    } else { 
     this.elements[index].set(indexes, value); 
    } 
    return this; 
} 

var m = new MultiArray([4, 3, 5]); 
m.set([1, 2, 4], "i'm a value in a multi dimensional array"); 
m.get([1, 2, 4]); // should return "i'm a value in a multi dimensional array" 
m.get([2, 0, 3]); // should return undefined 
m.get([0, 1]); // should return an array of 5 elements 
2

您可以使用這樣的事情:

function MultiArray(dimensions) { 
    var a = []; 
    if (dimensions > 1) { 
     a.push(MultiArray(dimensions -1)); 
    } 
    return a; 
} 
var m = MultiArray(4); 
+1

+1,但名稱可能更好,因爲它是工廠函數,而不是構造函數。 – Bergi 2014-10-07 21:22:14

+0

是的,你是可靠的,我從問題中得到名字 – Styx 2014-10-07 21:26:50