javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > JS find()、findIndex()、filter()、indexOf()处理数组

JavaScript中find()、findIndex()、filter()、indexOf()处理数组方法的具体区别详解

作者:碳烤小咸鱼

在JavaScript中数组是一种非常常见且功能强大的数据结构,这篇文章主要介绍了JavaScript中find()、findIndex()、filter()、indexOf()处理数组方法具体区别的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下

一、find()方法:

功能:返回第一个满足条件的元素,无符合项时返回 undefined

const numbers = [10, 20, 30, 40];
const result = numbers.find((num) => num > 25); 
console.log(result); 
//结果:30,因为30是数组numbers中第一个大于25的元素。

参数

特点

二、findIndex()方法:

功能:返回第一个满足条件的元素的索引,无符合项时返回 -1

const fruits = ['apple', 'banana', 'cherry', 'date'];
const index = fruits.findIndex((fruit) => fruit === 'cherry'); 
console.log(index); 
//结果:2,因为cherry在数组fruits中的索引是2。

参数:同 find()

特点

三、filter()方法:

功能:返回包含所有满足条件元素的新数组,原数组不变。

const scores = [75, 80, 60, 90];
const passingScores = scores.filter((score) => score >= 70); 
console.log(passingScores); 
//结果:[75, 80, 90],新数组passingScores包含了原数组scores中所有大于等于70的分数。

参数:同 find()

特点

四、indexOf()方法:

功能:返回指定元素首次出现的索引,无匹配时返回 -1

const colors = ['red', 'blue', 'green', 'blue'];
const blueIndex = colors.indexOf('blue'); 
console.log(blueIndex); 
//结果:1,因为blue在数组colors中第一次出现的索引是1。

参数

特点

五、方法对比与总结:

方法返回值使用场景是否遍历全部元素
find()元素复杂条件查找首个匹配项否(短路)
findIndex()索引复杂条件查找首个匹配索引否(短路)
filter()新数组筛选多个符合条件元素
indexOf()索引简单值查找首个匹配索引否(可指定起点)

六、兼容性:

总结 

到此这篇关于JavaScript中find()、findIndex()、filter()、indexOf()处理数组方法具体区别的文章就介绍到这了,更多相关JS find()、findIndex()、filter()、indexOf()处理数组内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文