1

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

4 回答 4

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指向我们当前所在的嵌套数组,并通过 for 读取从 currentindicies中查找下一个值。一旦我们到达列表中的最后一个索引,我们就找到了要存放值的数组。最终索引是我们存放值的最终数组中的插槽。arrayarrayindices

于 2012-06-13T16:51:23.587 回答
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;
}
于 2012-06-13T16:30:18.933 回答
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;
}
于 2012-06-13T16:43:21.197 回答
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");
};
于 2012-06-13T16:56:13.197 回答