[英]EcmaScript6 findIndex method, can it return multiple values?
在学习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做到这一点?
谢谢
findIndex()方法返回满足提供的测试功能的数组中第一个元素的索引。 否则返回-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);
您可以在此处使用.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));
只需使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.