可以使用类似于以下代码的函数来实现该问题:
function getSpecificItemsByIndex(arr, indices) {
return arr.filter((_, index) => indices.includes(index));
}
函数接受两个参数:一个数组和一个要检索的索引数组。该函数使用 filter()
方法来筛选匹配的索引对应的数组项。
例如,使用以下代码来测试该函数:
const myArr = ["apple", "banana", "orange", "grape", "peach"];
const myIndices = [0, 2, 4];
console.log(getSpecificItemsByIndex(myArr, myIndices)); // ["apple", "orange", "peach"]
该函数将输出数组中的第 1、 3 和 5 项,即 ["apple", "orange", "peach"]
。
上一篇:按索引返回数字的方法
下一篇:按索引范围划分区域