查找 JS 数组中所有元素出现的索引

目录

Find the Index of all Occurrences of an Element in JS Array

  1. 查找 JS 数组中所有元素出现的索引
  2. 使用以下方法查找数组中元素所有出现的索引reduce()
  3. 使用以下方法查找数组中元素所有出现的索引map()

查找元素在JS数组中所有出现的索引

获取数组中元素所有出现的索引:

  1. 声明一个新变量并将其初始化为一个空数组。
  2. 使用forEach()方法迭代原始数组。
  3. 检查每个元素是否等于指定值。
  4. 将匹配的元素推入新数组。
索引.js
const arr = ['a', 'b', 'a', 'c', 'a']; const indexes = []; arr.forEach((element, index) => { if (element === 'a') { indexes.push(index); } }); console.log(indexes); // 👉️ [ 0, 2, 4 ]

我们声明了一个新变量并将其初始化为一个空数组。

indexes变量将存储数组中所有出现的元素的索引。

我们传递给Array.forEach方法的函数
会针对数组中的每个元素进行调用。

在每次迭代中,我们检查当前元素是否等于指定值。

如果满足条件,我们将当前索引压入数组indexes

JavaScript 索引在 JavaScript 中是从零开始的,因此数组中的第一个元素的索引为0,最后一个元素的索引为 arr.length - 1

如果您必须经常这样做,请定义一个可重用的函数。

索引.js
function allOccurrences(arr, value) { const indexes = []; arr.forEach((element, index) => { if (element === value) { indexes.push(index); } }); return indexes; } const arr = ['a', 'b', 'a', 'c', 'a']; console.log(allOccurrences(arr, 'a')); // 👉️ [ 0, 2, 4 ] console.log(allOccurrences(arr, 'b')); // 👉️ [ 1 ] console.log(allOccurrences(arr, 'c')); // 👉️ [ 3 ]

该函数以一个数组和一个值作为参数,并返回数组中该值的所有索引。

或者,您可以使用该Array.reduce()方法。

使用以下方法查找数组中元素所有出现的索引reduce()

这是一个三步过程:

  1. 使用该Array.reduce()方法遍历数组。
  2. 检查当前元素是否等于指定值。
  3. 将匹配元素的索引推送到accumulator数组中。
索引.js
const arr = ['a', 'b', 'a', 'c', 'a']; const indexes = arr.reduce((accumulator, current, index) => { if (current === 'a') { accumulator.push(index); } return accumulator; }, []); console.log(indexes); // 👉️ [ 0, 2, 4 ]

我们传递给Array.reduce方法的函数
会为数组中的每个元素调用。

我们将accumulator变量初始化为数组,因为这是我们作为第二个参数传递给方法的内容reduce()

我们从回调函数返回的值将作为accumulator
下一次迭代传递。

在每次迭代中,我们检查当前元素是否等于特定值。

如果满足条件,我们将当前索引压入数组accumulator

否则,我们accumulator按原样返回数组。

在最后一次迭代之后,indexes数组存储该元素在数组中所有出现的索引。

使用以下方法查找数组中元素所有出现的索引map()

您还可以使用map()filter()方法查找数组中某个元素所有出现的索引。

索引.js
const arr = ['a', 'b', 'a', 'c', 'a']; const value = 'a'; const indexes = arr .map((element, index) => (element === value ? index : -1)) .filter(element => element !== -1); console.log(indexes); // 👉️ [ 0, 2, 4 ]

我们传递给Array.map()方法的函数

会针对数组中的每个元素进行调用。

map()方法返回一个新数组,其中包含从回调函数返回的值。

索引.js
const arr = ['a', 'b', 'a', 'c', 'a']; const value = 'a'; const indexes = arr.map((element, index) => element === value ? index : -1, ); console.log(indexes); // 👉️ [ 0, -1, 2, -1, 4 ]

对于每个不满足条件的元素,我们返回-1

最后一步是使用该方法从数组中Array.filter()删除值。-1

索引.js
const arr = ['a', 'b', 'a', 'c', 'a']; const value = 'a'; const indexes = arr .map((element, index) => (element === value ? index : -1)) .filter(element => element !== -1); console.log(indexes); // 👉️ [ 0, 2, 4 ]

我们传递给Array.filter方法的函数

会针对数组中的每个元素进行调用。

filter()方法返回一个只包含满足条件的元素的新数组。

额外资源

您可以通过查看以下教程来了解有关相关主题的更多信息: