如何在JavaScript数组中按间隔为特定类型元素插入新元素
How to Insert Elements into an Array Based on Element Type Counts (Avoiding forEach Iteration Issues)
Problem Statement
You have an initial array:
const initialArray = [ { type: 'all' }, { type: 'all' }, { type: 'all' }, { type: 'fruit'}, { type: 'all' }, { type: 'all' }, { type: 'fruit' }, { type: 'all' }, { type: 'all' }, { type: 'fruit' }, { type: 'fruit' } ];
Your requirements are:
- Insert
{type: 'toys'}after every 5 elements withtype: 'all' - Insert
{type: 'clothes'}after every 2 elements withtype: 'fruit'
The expected result is:
[ { type: 'all' }, { type: 'all' }, { type: 'all' }, { type: 'fruit'}, { type: 'all' }, { type: 'all' }, { type: 'toys' }, { type: 'fruit' }, { type: 'clothes' }, { type: 'all' }, { type: 'all' }, { type: 'fruit' }, { type: 'fruit' }, { type: 'clothes' } ];
When trying to use forEach directly on the original array, inserting elements modifies the array's length, which messes up the iteration (you end up processing new elements you just added, and lose track of the original elements). Your test code illustrates this issue:
array_demo.forEach((item, index) => { array_demo.push({type: 'demo'}); console.warn(index); });
Solution: Use a New Array to Collect Results
Instead of modifying the original array while iterating over it, create a new array to build your final result. Track counts of 'all' and 'fruit' elements as you iterate, and insert the required items into the new array when the counts hit your thresholds.
Here's the working code:
const initialArray = [ { type: 'all' }, { type: 'all' }, { type: 'all' }, { type: 'fruit'}, { type: 'all' }, { type: 'all' }, { type: 'fruit' }, { type: 'all' }, { type: 'all' }, { type: 'fruit' }, { type: 'fruit' } ]; const resultArray = []; let allCount = 0; let fruitCount = 0; initialArray.forEach(item => { // Add the current item to the result first resultArray.push(item); // Update counters and check for insertion conditions if (item.type === 'all') { allCount++; // Insert 'toys' after every 5 'all' elements if (allCount === 5) { resultArray.push({ type: 'toys' }); allCount = 0; // Reset counter after insertion } } else if (item.type === 'fruit') { fruitCount++; // Insert 'clothes' after every 2 'fruit' elements if (fruitCount === 2) { resultArray.push({ type: 'clothes' }); fruitCount = 0; // Reset counter after insertion } } }); console.log(resultArray); // This matches your expected output
Why This Works
- We never modify the original
initialArrayduring iteration, soforEachprocesses exactly the 11 elements you started with—no more, no less. - The counters (
allCountandfruitCount) keep track of how many qualifying elements we've added to the result array so far. When we hit the threshold, we insert the required item and reset the counter to start tracking the next set.
内容的提问来源于stack exchange,提问作者Dicky Chan
相关产品推荐
相关产品推荐

