简体   繁体   English

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

[英]EcmaScript6 findIndex method, can it return multiple values?

While learning ES6 and i was trying to find the index of multiple items on an Array, but i just got the index of the first item that match with my condition or callback function. 在学习ES6时,我试图在一个数组上查找多个项目的索引,但是我只是得到了与我的条件或回调函数匹配的第一个项目的索引。

Example: I have an Array with ages and i want the index of all the ages over or equals to 18. 示例:我有一个带有年龄的数组,我希望所有年龄的索引大于或等于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 

So i want to understand if the Array.prototype.findIndex() method just return the single index of the first item that match or -1 is any item satisfies the condition. 因此,我想了解Array.prototype.findIndex()方法是否仅返回匹配的第一个项目的单个索引,或者-1是满足条件的任何项目。 And how can we do it using ES6? 以及如何使用ES6做到这一点?


Thanks 谢谢

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. findIndex()方法返回满足提供的测试功能的数组中第一个元素的索引。 Otherwise -1 is returned. 否则返回-1。

One option is using reduce instead. 一种选择是使用reduce Use concat to add the index to accumulator if the number is greater than or equal to 18 如果数字大于或等于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); 

You can use .map() method here like: 您可以在此处使用.map()方法,例如:

 let ages = [12, 15, 18, 17, 21]; let indexes = ages.map((elm, idx) => elm >= 18 ? idx : '').filter(String); console.log( indexes ); 

The syntax for the .map() method is like: .map()方法的语法如下:

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
    // Return element for new_array
}[, thisArg])

where we can use currentValue and index for our requirement. 在这里我们可以使用currentValueindex来满足我们的需求。

And a generic function for it can be like: 它的通用函数可能像这样:

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

Simply use Array.reduce() and make array of index of all ages greater than 18. 只需使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM