filter find includes indexOf
Array.filter()
在数组中查找满足特定条件的元素
let newArray = array.filter(callback);
newArray是返回的新数组 array 是我们要进行查找的数组本身 callback 是应用于数组每个元素的回调函数如果数组中没有项目符合条件,则返回一个空数组。
例如,如果我们要获取大于10的数字数组中的所有项目,则可以执行以下操作: const array = [10, 11, 3, 20, 5]; const greaterThanTen = array.filter(element => element > 10); console.log(greaterThanTen) //[11, 20]
Array.find()
查找满足特定条件的第一个元素
let element = array.find(callback);
element -当前被遍历的元素(必填) index -当前遍历的元素的索引/位置(可选) array- 当前数组(可选)但是请注意,如果数组中没有项目符合条件,则返回 undefined。
const array = [10, 11, 3, 20, 5]; const greaterThanTen = array.find(element => element > 10); console.log(greaterThanTen)//11
Array.includes()
确定数组是否包含某个值,并在适当时返回 true 或 false
const includesValue = array.includes(valueToFind, fromIndex)
valueToFind 是要在数组中检查的值(必填) fromIndex 是要开始从中搜索元素的数组中的索引或位置(可选)检查20是否为数组中的元素之一,则可以执行以下操作: const array = [10, 11, 3, 20, 5]; const includesTwenty = array.includes(20); console.log(includesTwenty)//true 如果要检查数组是否在第一个元素之外的其他位置包含10个,可以执行如下操作: const array = [10, 11, 3, 20, 5]; const includesTenTwice = array.includes(10, 1); console.log(includesTenTwice)//false
Array.indexOf()
返回可以在数组中找到给定元素的第一个索引。如果数组中不存在该元素,则返回 -1
const indexOfElement = array.indexOf(element, fromIndex)
element 是要在数组中检查的元素(必填),并且 fromIndex 是要从数组中搜索元素的启始索引或位置(可选)请务必注意,includes 和 indexOf 方法都使用严格的相等性('===')搜索数组。如果值的类型不同(例如4和'4'),它们将分别返回 false 和 -1
让我们找到数组中 3 的索引。 const array = [10, 11, 3, 20, 5]; const indexOfThree = array.indexOf(3); console.log(indexOfThree)//2
结语
无需使用 for 循环即可搜索数组
如果你想找到在符合特定条件的阵列中的所有项目,使用 filter。 如果你想检查是否至少有一个项目符合特定的条件,请使用 find。 如果你想检查一个数组包含一个特定的值,请使用 includes。 如果要在数组中查找特定项目的索引,请使用indexOf到此这篇关于JavaScript常用数组元素搜索或过滤的四种方法的文章就介绍到这了,更多相关js搜索数组元素内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
查看更多关于JavaScript常用数组元素搜索或过滤的四种方法详解的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did121305