使用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()
遍历 indexes
并获取您想要的元素.
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屋!
查看全文