JavaScript中有選擇多維數組元素的方法嗎?深度/等級/維度是可變的,並且密鑰由一系列索引給出。這樣我就沒有分開處理每個可能的維度深度。具體來講,我想辦擺脫開關情況下,像在這裏: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;
}
預先感謝您!
可能重複[array.contains(obj)in JavaScript](http://stackoverflow.com/questions/237104/array-containsobj-in-javascript) –