数组的indexOf和findIndex函数之间的区别 [英] Difference Between indexOf and findIndex function of array

查看:1409
本文介绍了数组的indexOf和findIndex函数之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对两个函数indexOf和在数组中查找Index之间的区别感到困惑。

I am confused between the difference between the two function indexOf and find Index in an array.

文档说


findIndex - 返回数组中第一个元素的索引,其中
谓词为真,否则为-1。

findIndex - Returns the index of the first element in the array where predicate is true, and -1 otherwise.


indexOf - 返回$ b $中第一次出现的值的索引b array。

indexOf - Returns the index of the first occurrence of a value in an array.


推荐答案

主要区别在于这些函数的参数:

The main difference are the parameters of these functions:

  • Array.prototype.indexOf() expects a value as first parameter. This makes it a good choice to find the index in arrays of primitive types (like string, number, or boolean).

Array.prototype.findIndex() 需要回调作为第一个参数。如果您需要具有非基本类型(例如对象)的数组中的索引,或者您的查找条件比仅仅值更复杂,请使用此选项。

Array.prototype.findIndex() expects a callback as first parameter. Use this if you need the index in arrays with non-primitive types (e.g. objects) or your find condition is more complex than just a value.

有关这两种情况的示例,请参阅链接。

See the links for examples of both cases.

这篇关于数组的indexOf和findIndex函数之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆