如何基于索引数组获取值数组?
问题描述:
我有一组两个数组.一个包含一些水果值作为字符串,另一个包含一些随机数.在这里,我认为数字数组是水果数组的索引.给定索引数组中的数字,如何获得新的水果数组?
I have a set of two arrays. One contains some fruit values as strings, the other one contains some random numbers. Here I considered the number arrays are the indexes of the fruits array. How to get a new array of fruits given the numbers in the index array?
示例代码:
var resultArr = [];
var fruitier = ["apple", "orange", "grapes", "pineapple", "fig", "banana", "jackfruit", "pomegranate"];
var indexArr = [0, 2, 4];
输出:
resultArr = ["apple", "grapes", "fig"];
答
for(var i = 0; i < indexArr.length; i++)
resultArr.push(fruitier[indexArr[i]]);