gpt4 book ai didi

javascript - EcmaScript6 findIndex 方法,它可以返回多个值吗?

转载 作者:行者123 更新时间:2023-12-03 17:46:32 25 4
gpt4 key购买 nike

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

谢谢

最佳答案

您可以使用 .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));

关于javascript - EcmaScript6 findIndex 方法,它可以返回多个值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51158401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com