javascript - 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 来做到这一点?
谢谢
解决方案
您可以.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));
推荐阅读
- jquery - Zendesk API 无效响应
- java - 如何重启 Kubernetes 服务的多个 Spring Boot 应用程序实例
- objective-c - 嵌套 NSMutableDictionary 对象的 valueForKeyPath 失败
- synthesis - 如何在 Chisel 中用 ASIC 单元替换组合存储器
- search - Lucene/AzureSearch 最接近的匹配项
- r - R帮助计算几年内几个月的平均值
- docker - docker:使用屏幕通过 cron 作业关闭我的世界服务器不起作用
- python - 在 Apache Beam 2.9 上导入 cloud-spanner 时出错
- amazon-web-services - 如何获取 ec2 实例的 publci Ip 并将其传递给 jenkins 以构建容器?
- java - 错误的数字格式