JavaScript中是否存在动态维数组这样的东西?

时间:2014-10-07 20:53:00

标签: javascript arrays dynamic multidimensional-array

动态维数组的意思是具有各种维度的多维数组。我需要创建一个函数,它对多维数组的元素执行某些操作,而不管它们的大小。我编写了一个应该循环遍历多维数组的所有元素的函数,但是我无法找到获取它们的方法。这是我写的:

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]);,就像调用{4}数组的MultiArray([4,6]);一样,或者MultiArray([7]);调用一个4x6数组 - 加长数组。

2 个答案:

答案 0 :(得分:2)

您可以使用以下内容:

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

答案 1 :(得分: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