JavaScript常用数组元素搜索或过滤的四种方法 |
您所在的位置:网站首页 › 怎么在审查元素中查找东西 › JavaScript常用数组元素搜索或过滤的四种方法 |
获取满足特定条件的数组中的所有项目要检查是否满足条件?检查数组中是否有特定值?在数组中找到指定值的索引?
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 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |