JavaScript中索引数组的多维索引

时间:2012-06-13 16:27:26

标签: javascript arrays indexing switch-statement multidimensional-array

JavaScript中有没有办法选择多维数组的元素。深度/等级/维度是可变的,并且键由索引数组给出。这样我就没有分别处理每个可能的尺寸深度。具体来说,我想摆脱像这里的开关案例:

/**
 * set tensor value by index
 * @type {array} indices [ index1, index2, index3 ] -> length == rank.
 * @type {string} value.
 */
tensor.prototype.setValueByIndex = function( indices, value ) {
    var rank = indices.length;

    switch(rank) {
        case 0:
            this.values[0] = value;
        break;
        case 1:
            this.values[indices[0]] = value;
        break;
        case 2:
            this.values[indices[0]][indices[1]] = value;
        break;
        case 3:
            this.values[indices[0]][indices[1]][indices[2]] = value;
        break;
    }
}

this.values 是多维数组。

这样我得到的东西看起来更像是这样:

/**
 * set tensor value by index
 * @type {array} indices, [ index1, index2, index3 ] -> length == rank
 * @type {string} value
 */
tensor.prototype.setValueByIndex = function( indices, value ) {
    var rank = indices.length;

    this.values[ indices ] = value;
}

提前谢谢!

4 个答案:

答案 0 :(得分:2)

tensor.prototype.setValueByIndex = function( indices, value ) {
    var array = this.values;
    for (var i = 0; i < indices.length - 1; ++i) {
        array = array[indices[i]];
    }
    array[indices[i]] = value;
}

这使用array指向我们当前所在的嵌套数组,并通过indicies读取以查找当前array的下一个array值。一旦我们到达indices列表中的最后一个索引,我们就找到了要存放值的数组。最终索引是我们存入值的最终数组中的插槽。

答案 1 :(得分:1)

喜欢这个吗?

tensor.prototype.setValueByIndex = function( indices, value ) {
  var t = this, i;
  for (i = 0; i < indices.length - 1; i++) t = t[indices[i]];
  t[indices[i]] = value;
}

答案 2 :(得分:1)

这样的事情:

tensor.prototype.setValueByIndex = function( indexes, value ) {
    var ref = this.values;  
    if (!indexes.length) indexes = [0];  
    for (var i = 0; i<indexes.length;i++) {
       if (typeof ref[i] === 'undefined') ref[i] = [];
       if (ref[i] instanceof Array) {  
           ref = ref[i];
       } else {
           throw Error('There is already value stored') 
       }
    } 
    ref = value;
}

答案 3 :(得分:1)

你为什么要那样做?我会说写作

tensor.values[1][5][8][2] = value;

更明显
tensor.setValues([1, 5, 8, 2], value);

如果你真的需要这样做,它将是一个简单的数组循环:

tensor.prototype.setValueByIndex = function(indices, value) {
    var arr = this.values;
    for (var i=0; i<indices.length-1 && arr; i++)
        arr = arr[indices[i]];
    if (arr)
        arr[indices[i]] = value;
    else
        throw new Error("Tensor.setValueByIndex: Some index pointed to a nonexisting array");
};