使用javascript中的索引数组索引数组数组 [英] Index an array of arrays with an array of indexes in javascript
本文介绍了使用javascript中的索引数组索引数组数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定数组[of arrays ...]数组,例如:
Given an array of arrays [of arrays ...] such as:
array[a][b][c][d][e]
以及一系列索引:
indexes = [ a, b, c, d, e ];
是否有一种使用索引数组索引数组数组的优雅方法?
Is there an elegant way to index the array of arrays using the array of indexes?
我使用的暴力方法是:
element = array[indexes[0]][indexes[1]][indexes[2]][indexes[3]][indexes[4]]
编辑
要清楚,我将能够使用1到n个元素的任意索引数组,其中n是数组嵌套的深度。
To be clear, I would to be able to use an arbitrary array of indexes from 1 to n elements, where n is the depth of array nesting.
所以给出上面的五级嵌套数组数组的例子,并给出一个索引数组:
So given the above example of five-level nested array of arrays, and given an index array of:
indexes2 = [ a, b, c ];
我希望检索:
array[a][b][c]
推荐答案
您可以使用 Array.reduce()
通过索引
并获取所需的元素。
You can use Array.reduce()
to go through the indexes
and get the element you want.
// array[a][b][c][d][e]
var indexes = [ a, b, c, d, e ];
var element = indexes.reduce(function(prev, curr){
return prev[curr];
}, array);
这篇关于使用javascript中的索引数组索引数组数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文