You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按索引奇偶性筛选数组生成两个新数组?代码求助

正确筛选数组中索引奇偶元素的实现方案

原代码的问题

你的代码有两个核心错误:

  • filter回调函数的第一个参数是当前元素的值,不是索引,你需要用到第二个参数(索引)来判断位置
  • 返回语句arr[i % 2 === 0]逻辑完全错误,这相当于用布尔值作为数组下标去取值,完全不符合筛选需求

正确实现方案

方案1:使用filter分别筛选

利用filter的第二个参数(元素索引)来判断奇偶性,分别生成两个数组:

let arr = [1, 4, 5, 2, 8, 9, 7, 10];

// 索引为偶数的元素(索引从0开始)
const evenIndexElements = arr.filter((_, index) => index % 2 === 0);
// 索引为奇数的元素
const oddIndexElements = arr.filter((_, index) => index % 2 !== 0);

console.log(evenIndexElements); // 输出: [1, 5, 8, 7]
console.log(oddIndexElements); // 输出: [4, 2, 9, 10]

注:_是占位符,表示我们不需要使用当前元素的值。

方案2:单次遍历填充两个数组(性能更优)

如果处理大数组,单次遍历比两次filter更高效:

let arr = [1, 4, 5, 2, 8, 9, 7, 10];
const evenIndexElements = [];
const oddIndexElements = [];

arr.forEach((item, index) => {
  index % 2 === 0 ? evenIndexElements.push(item) : oddIndexElements.push(item);
});

console.log(evenIndexElements); // 输出: [1, 5, 8, 7]
console.log(oddIndexElements); // 输出: [4, 2, 9, 10]

内容的提问来源于stack exchange,提问作者Trương Khôi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 01:14:55