JavaScript查找数组中指定元素的索引的方法小结
更新时间:2026年01月19日 09:21:36 作者:Never_Satisfied
这篇文章主要介绍了JavaScript中查找数组元素索引的五种方法:indexOf()、lastIndexOf()、findIndex()、findLastIndex()和手动循环,每种方法都有其适用场景和返回值,手动循环在性能上可能更优,选择时应考虑具体需求和数组大小,需要的朋友可以参考下
在 JavaScript 中,有几种方法可以查找数组中指定元素的索引:
1. indexOf() - 查找简单值
const arr = ['apple', 'banana', 'orange', 'banana'];
// 查找第一个匹配项的索引
console.log(arr.indexOf('banana')); // 1
// 查找不存在的元素
console.log(arr.indexOf('grape')); // -1
// 从指定位置开始查找
console.log(arr.indexOf('banana', 2)); // 3
2. lastIndexOf() - 从后往前查找
const arr = ['apple', 'banana', 'orange', 'banana'];
console.log(arr.lastIndexOf('banana')); // 3
console.log(arr.lastIndexOf('banana', 2)); // 1
3. findIndex() - 使用回调函数查找
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
// 查找第一个满足条件的元素索引
const index = users.findIndex(user => user.name === 'Bob');
console.log(index); // 1
// 查找年龄大于25的用户索引
const ages = [18, 22, 30, 45];
const ageIndex = ages.findIndex(age => age > 25);
console.log(ageIndex); // 2
4. findLastIndex() - 从后往前使用回调函数查找
const numbers = [1, 2, 3, 4, 3, 5]; // 从后往前查找第一个满足条件的元素索引 const lastIndex = numbers.findLastIndex(num => num === 3); console.log(lastIndex); // 4
5. 手动循环实现
function findIndexCustom(arr, value) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === value) {
return i;
}
}
return -1;
}
const arr = ['a', 'b', 'c'];
console.log(findIndexCustom(arr, 'b')); // 1
console.log(findIndexCustom(arr, 'd')); // -1
实际应用示例
// 查找对象数组中的特定元素
const products = [
{ id: 1, name: 'Laptop', price: 1000 },
{ id: 2, name: 'Phone', price: 500 },
{ id: 3, name: 'Tablet', price: 300 }
];
// 查找价格低于400的产品索引
const cheapProductIndex = products.findIndex(product => product.price < 400);
console.log(cheapProductIndex); // 2
// 查找所有匹配项的索引
function findAllIndexes(arr, value) {
const indexes = [];
let currentIndex = -1;
while ((currentIndex = arr.indexOf(value, currentIndex + 1)) !== -1) {
indexes.push(currentIndex);
}
return indexes;
}
const fruits = ['apple', 'banana', 'apple', 'orange', 'apple'];
console.log(findAllIndexes(fruits, 'apple')); // [0, 2, 4]
总结
- 简单值查找:使用
indexOf()或lastIndexOf() - 复杂条件查找:使用
findIndex()或findLastIndex() - 返回值:所有方法在未找到时都返回
-1 - 性能考虑:对于大型数组,
indexOf()通常比手动循环更快
根据具体需求选择合适的方法!
到此这篇关于JavaScript查找数组中指定元素的索引的方法小结的文章就介绍到这了,更多相关JS查找数组中指定元素的索引内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
在JavaScript 中按字母排序之如何在 JS 中按名称排序
有时你可能有一个单词数组,你想按字母顺序(从 a-z)对每个单词进行排序,或者你可能有一个包含用户信息(包括名字)的对象数组,例如,你想按照用户的名字来排序,接下来通过本文给大家介绍在JavaScript 中按字母排序之如何在 JS 中按名称排序,需要的朋友可以参考下2023-09-09


最新评论