在JS中使用索引值数组来访问数组的一部分



我试图找到一种方法来访问具有特定索引的数组的一部分,并且索引也在数组中。所以,我有这样的东西:

var arr = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven'];
var arrIndexes = [1, 3, 5];

我正在寻找一种使用arrIndexes访问arr的特定部分的简单方法,因此我的输出将简单地为['one', 'three', 'five']

您可以通过使用Array.prototype.map()来稍微减少计算量:

var arr = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven'];
var arrIndexes = [1, 3, 5];
const res = arrIndexes.map(i=>arr[i])
console.log(res);

可以通过使用Array.prototype.filter()includes()函数来实现。试试这个,

var arr = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven'];
var arrIndexes = [1, 3, 5];
const res = arr.filter((item, index) => arrIndexes.includes(index));
console.log(res);

你可以像这样使用reduce函数

let newAr=arr.reduce((prev,curr,idx,arr)=>{
if(arrIndexes.includes(idx)){
prev.push(arr[idx]);
}
return prev;
},[])

最新更新