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

如何将数组奇偶位置元素拆分的for循环改写为forEach循环

Convert Array Splitting Logic from for Loop to forEach()

Got it, let's work through this together. You need to split an array into two separate arrays—one for elements in odd positions (1st, 3rd, 5th, etc.) and another for even positions (2nd, 4th, 6th, etc.)—and you want to convert your existing for loop code to use forEach() instead.

First, let's confirm the original logic to make sure we're aligned:

  • Elements at even indices (0, 2, 4...) go into the odd array (since these map to the 1st, 3rd, 5th positions in the original array)
  • Elements at odd indices (1, 3, 5...) go into the even array (mapping to 2nd, 4th, 6th positions)

Here's how you can rewrite this with forEach():

// Initialize empty arrays to hold our results
const odd = [];
const even = [];

// Your target array (replace with your actual array)
const arr1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];

// Use forEach, leveraging the index parameter to determine position
arr1.forEach((element, index) => {
  // Check if the index is even (since index starts at 0)
  if (index % 2 === 0) {
    odd.push(element);
  } else {
    even.push(element);
  }
});

// Verify the output
console.log(odd); // Output: ['a', 'c', 'e', 'g']
console.log(even); // Output: ['b', 'd', 'f']

This logic is identical to your original for loop. Let's break down why: your original condition (i+2)%2 === 1 simplifies to i%2 === 1 (adding 2 doesn't change a number's parity). So when the index is odd, you push to even—which matches our else clause here.

A few quick tips:

  • I used const instead of var because we don't reassign the arrays—this is modern JS best practice, but feel free to switch back to var if you need to support older environments.
  • forEach() handles the loop iteration automatically, so you don't have to manage a counter variable, making the code cleaner and less error-prone.

If you prefer a more concise version, you can use a ternary operator inside the callback:

arr1.forEach((el, idx) => {
  idx % 2 === 0 ? odd.push(el) : even.push(el);
});

Stick with the first version if readability is a priority, though—it's easier for other developers (or future you) to parse at a glance.

内容的提问来源于stack exchange,提问作者user6514554

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:47:15