Difference Between indexOf and findIndex function of array
我对两个函数indexOf和数组中的Find Index之间的区别感到困惑。
文档说
findIndex - Returns the index of the first element in the array where
predicate is true, and -1 otherwise.
和
indexOf - Returns the index of the first occurrence of a value in an
array.
主要区别在于这些功能的参数:
-
Array.prototype.indexOf() 需要一个值作为第一个参数。这是在原始类型(如字符串,数字或布尔值)的数组中查找索引的不错选择。 -
Array.prototype.findIndex() 希望将回调作为第一个参数。如果您需要非原始类型(例如对象)类型的数组中的索引,或者您的查找条件比一个值更复杂,请使用此选项。
有关两种情况的示例,请参见链接。
如果要查找与谓词匹配的第一个元素,则
FindIndex很有用:在W3C的示例中,如果客户的年龄大于或等于18,则存在数字和匹配项。
1 2 3 4 5 6 7 | var ages = [3, 10, 18, 20]; function checkAdult(age) { return age >= 18; } console.log(ages.findIndex(checkAdult)); |
控制台:
1 | 2 |
您可以使用Array的indexOf函数找到确切的元素索引,但不能传递谓词。如果要查找特定元素,则速度更快:
1 2 | var ages = [3, 10, 18, 20]; console.log(ages.indexOf(10)); |
返回:
1 | 1 |
索引计数从0开始,因此第一个元素索引为0。
另一个区别是
使用findIndex(),用户可以应用某些功能并在通过测试的数组中查找元素。
但对于indexOf()运算符而言并非如此。
用户可以只检查数组中是否存在特定元素。
简单-您使用哪种数组结构?
-
如果是对象数组,则为
findIndex() ; -
其他,
indexOf() 。
"我想用键"橙色"在对象数组中找到索引。
1 2 3 4 5 6 7 8 | let fruits = [ { type:"Apple", quantity: 9 }, { type:"Banana", quantity: 2}, { type:"Orange", quantity: 8}, { type:"Pear", quantity: 777} ]; let myIndex = fruits.findIndex(fruit => fruit.type ==="Orange"); // Returns 2. |
"我想在一个简单的数组中找到索引"。
1 2 3 | let fruits = ["Apple","Banana","Pear","Orange"]; let index = fruits.indexOf("Orange"); // Returns 3. |
主要区别在于这些功能的参数:
->
Array.prototype.indexOf():
1 2 3 | var fruits = ["Banana","Orange","Apple","Mango"]; var a = fruits.indexOf("Apple"); The result of a will be: 2 |
-> Array.prototype.findIndex():
1 2 3 4 5 6 7 8 9 10 11 12 | var ages = [3, 10, 18, 20]; function checkAdult(age) { return age >= 18; } function myFunction() { document.getElementById("demo").innerHTML = ages.findIndex(checkAdult); } The result will be: 2 |
您也可以使用
1 2 3 | [1, 2, 3].includes(2); // true [1, 2, 3].includes(4); // false [1, 2, 3].includes(3, 3); // false |
但我更喜欢
1 2 3 4 | var vals = ["foo","bar", 42,"baz" ]; if (~vals.indexOf( 42 )) { // found it! } |
您可以尝试以下代码:-
1 2 3 4 5 6 7 | let city = ['Delhi', 'mumbai'] const a = city.findIndex((item) => item.toLowerCase()==='delhi') console.log(a) // returns 0 let c = city.indexOf('mumbai') // returns 1 console.log(c) |