📅  最后修改于: 2023-12-03 15:12:26.751000             🧑  作者: Mango
如果你经常使用 JavaScript 操作数组,你可能会遇到需要获取数组元素在数组中的索引位置的情况。本文将介绍如何通过键值获取数组索引。
假设我们有一个数组,如下所示:
let myArray = ['apple', 'banana', 'cherry', 'apple', 'orange'];
如果要查找 'cherry' 的索引,我们可以使用 indexOf()
方法来查找:
let index = myArray.indexOf('cherry');
console.log(index); // 2
这将输出 2
,表示 'cherry' 在数组中的索引是 2。
但是,如果有多个相同的元素,例如上面的例子中有两个 'apple',我们只能在第一个 'apple' 的索引位置上返回结果:
let index = myArray.indexOf('apple');
console.log(index); // 0
在这种情况下,我们希望查找 'apple' 在数组中的所有索引位置。这时我们可以使用 reduce()
方法:
let indices = myArray.reduce((accumulator, currentValue, currentIndex) => {
if (currentValue === 'apple') {
accumulator.push(currentIndex);
}
return accumulator;
}, []);
console.log(indices); // [0, 3]
这将输出一个包含所有 'apple' 的索引的数组 [0, 3]
。
另一种获取数组索引的方法是使用 findIndex()
方法。该方法将在数组中查找满足指定条件的第一个元素,并返回它的索引:
let index = myArray.findIndex(element => element === 'cherry');
console.log(index); // 2
如果没有找到符合条件的元素,该方法将返回 -1
。
我们也可以使用 lastIndexOf()
方法来查找元素在数组中的最后一个索引位置:
let index = myArray.lastIndexOf('apple');
console.log(index); // 3
以上是通过键值 JS 获取数组索引的几种常见方法。在实际开发中,根据具体情况选择合适的方法进行操作,可以提高代码的质量和效率。
参考资料: