在学习ES6的同时,我试图在一个数组上查找多个项目的索引,但是我只是得到了与我的条件或回调函数匹配的第一个项目的索引。
示例: 我有一个带有年龄的数组,我希望所有年龄的索引都大于或等于18。
let ages = [12,15, 18, 17, 21];
console.log(`Over 18: ${ages.findIndex(item => item >= 18)}`);
// output that i'm looking: [2,4]
// output that is coming: 2
因此,我想了解Array.prototype.findIndex()
方法是否只返回匹配的第一个项目的单个索引,或者-1
是否满足条件。以及如何使用ES6做到这一点?
谢谢
答案 0 :(得分:3)
您可以在此处使用.map()
方法,
let ages = [12, 15, 18, 17, 21];
let indexes = ages.map((elm, idx) => elm >= 18 ? idx : '').filter(String);
console.log( indexes );
.map()
方法的语法如下:
var new_array = arr.map(function callback(currentValue[, index[, array]]) {
// Return element for new_array
}[, thisArg])
我们可以根据需要使用currentValue
和index
。
它的通用函数可以像这样:
const ages = [12, 15, 18, 17, 21];
const getAllIndexes = (arr, val) => {
return arr.map((elm, idx) => elm >= val ? idx : '').filter(String);
}
console.log(getAllIndexes(ages, 18));
console.log(getAllIndexes(ages, 17));
答案 1 :(得分:2)
findIndex()方法返回元素中 first 元素的索引。 满足提供的测试功能的数组。否则-1为 返回。
一种选择是使用reduce
。如果数字大于或等于18,请使用concat
将索引添加到累加器
let ages = [12, 15, 18, 17, 21];
let result = ages.reduce((c, v, i) => v >= 18 ? c.concat(i) : c, []);
console.log(result);
答案 2 :(得分:1)
只需使用Array.reduce()
并使所有年龄大于18的索引数组。
let ages = [12,15, 18, 17, 21];
var result = ages.reduce((a,curr,index)=>{
if(curr >= 18)
a.push(index);
return a;
},[]);
console.log(result);