了解 Javascript / Typescript 中的 findIndex

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44661490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:39:20  来源:igfitidea点击:

Understanding findIndex in Javascript / Typescript

javascripttypescript

提问by Ben Spi

I am working on a piece of JS code. In a tutorial I found a piece of code I don't understand:

我正在处理一段 JS 代码。在一个教程中,我发现了一段我不明白的代码:

const position = this.quotes.findIndex((quoteEl: Quote) => {
  return quoteEl.id == quote.id;
});

I think the person who wrote the code stuffed a lot of different pieces into this line. Can somebody help me bring that into a more "easy to understand" form?

我认为编写代码的人将很多不同的部分塞进了这一行。有人能帮我把它变成更“容易理解”的形式吗?

For example, the argument of the findIndex method can probably written in a separate function, right?

比如findIndex方法的参数应该可以写成一个单独的函数吧?

Thanks, Benjamin

谢谢,本杰明

回答by monkapish

findIndexcalls the passed function with each element of the array and returns the index of the first element that returned true, or -1if none did.

findIndex使用数组的每个元素调用传递的函数,并返回第一个返回的元素的索引true,或者-1如果没有返回。

This is your callback function

这是你的回调函数

(quoteEl: Quote) => {
  return quoteEl.id == quote.id;
}