简体   繁体   English

JavaScript是否有indexOf(lambda)或类似的?

[英]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 . 是的,有这样的功能: Array.prototype.findIndex The method was introduced by ECMAScript 2015 and you need to use a polyfill for supporting older browsers. 该方法由ECMAScript 2015引入,您需要使用polyfill来支持旧版浏览器。

是的它存在:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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