首页 > 解决方案 > EcmaScript6 findIndex 方法,它可以返回多个值吗?

问题描述

在学习 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 来做到这一点?


谢谢

标签: javascriptarraysecmascript-6

解决方案


您可以.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])

我们可以使用的地方currentValueindex我们的要求。

它的通用函数可以是:

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));


推荐阅读