javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > JS查找数组中指定元素的索引

JavaScript查找数组中指定元素的索引的方法小结

作者: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]

总结

根据具体需求选择合适的方法!

到此这篇关于JavaScript查找数组中指定元素的索引的方法小结的文章就介绍到这了,更多相关JS查找数组中指定元素的索引内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

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