方法一:使用 for 循环或者forEach()方法遍历数组
function findIndices(arr, condition) {
const indices = [];
for (let i = 0; i < arr.length; i++) {
if (condition(arr[i])) {
indices.push(i);
}
}
return indices;
}
// 示例用法
const numbers = [1, 2, 3, 1, 4, 1, 5, 1];
const indices = findIndices(numbers, num => num === 1);
console.log(indices); // 输出: [0, 3, 5, 7]
或者
function findIndexes(arr, target) {
let indexes = [];
arr.forEach((element, index) => {
if (element === target) {
indexes.push(index);
}
});
return indexes;
}
let arr = [1, 2, 3, 4, 2, 5, 2];
let target = 2;
console.log(findIndexes(arr, target)); // 输出 [1, 4, 6]
方法二:使用数组的 reduce方法
function findIndices(arr, condition) {
return arr.reduce((indices, element, index) => {
if (condition(element)) {
indices.push(index);
}
return indices;
}, []);
}
// 示例用法
const fruits = ['apple', 'banana', 'orange', 'banana', 'mango'];
const indices = findIndices(fruits, fruit => fruit === 'banana');
console.log(indices); // 输出: [1, 3]
方法三:使用Array.prototype.map()和Array.prototype.filter()方法结合
function findIndexes(arr, target) {
return arr.map((element, index) => {
if (element === target) {
return index;
}
}).filter(index => index !== undefined);
}
let arr = [1, 2, 3, 4, 2, 5, 2];
let target = 2;
console.log(findIndexes(arr, target)); // 输出 [1, 4, 6]
或者
function findIndices(arr, condition) {
return arr
.map((element, index) => ({ element, index })) // 将元素和索引组成对象
.filter(({ element }) => condition(element)) // 过滤出满足条件的对象
.map(({ index }) => index); // 获取满足条件的元素在原数组中的索引
}
// 示例用法
let arr4 = [1, 2, 3, 1, 4, 1, 5, 1];
let targets4 = findIndices(numbers, num => num === 1);
console.log(indices); // 输出: [0, 3, 5, 7]
方法四:递归
function findIndexes(arr, target, index = 0, result = []) {
if (index < arr.length) {
if (arr[index] === target) {
result.push(index);
}
findIndexes(arr, target, index + 1, result);
}
return result;
}
let arr = [1, 2, 3, 4, 2, 5, 2];
let target = 2;
console.log(findIndexes(arr, target)); // 输出 [1, 4, 6]