JavaScript ——找出数组中满足特定要求的所有数据的位置

方法一:使用 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]
  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值