【发布时间】:2021-11-05 21:53:11
【问题描述】:
当循环时满足特定条件时,通过在特定索引中插入新元素来更新数组的最佳方法是什么。
const exampleArray = [
{item: 1, count: 5},
{item: 2, count: 20},
{item: 3, count: 10},
{item: 6, count: 9}
{item: 4, count: 5}]
我想在跟踪计数的同时循环 exampleArray,并在计数大于或等于 10 时立即插入新元素,然后将计数重置为 0 以进行下一个循环
所以我想要的结果是
const resultArray = [
{item: 1, count: 5},
{item: 2, count: 20},
{item: 'new item 1 as count is over 10', count: 0},
{item: 3, count: 10},
{item: 'new item 2 as count is equal to 10', count: 0},
{item: 6, count: 9},
{item: 4, count: 5},
{item: 'new item 3 as count is > 10, previous two counts (9 + 5 )', count: 0 }]
我试过了
let count = 0
exampleArray.forEach((item, index) => {
count += item.count
if(count >= 10) {
exampleArray.splice(index + 1, 0, {item: 'item to be added', count: 0}
count = 0
}
})
【问题讨论】:
-
阅读developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 下的警告 - 这可能是最简单的,如果您在循环时不尝试弄乱现有数组,而是创建一个新的结果数组。
-
{item: 6, count: 9}是从哪里出现的?
标签: javascript arrays