简体   繁体   中英

Does JavaScript have an indexOf(lambda) or similar?

I want to return the index of the first element satisfying a unary predicate.

Example:

[1,2,3,4,5,6,7].indexOf((x) => x % 3 === 0) // returns 2

Is there such a function? The alternative I was going to use was

[1,2,3,4,5,6,7].reduce((retval,curelem,idx) => 
{
   if(curelem % 3 === 0 && retval === undefined)
       retval = idx; 
   return retval;
}, undefined);

but of course that would be less efficient since it doesn't stop iterating through the array after it has found the element.

Yes, there is such function: Array.prototype.findIndex . The method was introduced by ECMAScript 2015 and you need to use a polyfill for supporting older browsers.

是的它存在:

console.log([1,2,3,4,5,6,7].findIndex((x) => x % 3 === 0));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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