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

求JavaScript实现数组末位元素递减弹除直至为空的循环方案

数组迭代逻辑实现需求

迭代示例

Array = [ 1, 3, 7, 2 ]

1st Iteration = [ 1, 3, 7, 1 ]
2nd Iteration = [ 1, 3, 7, 0 ]
3rd Iteration = [ 1, 3, 6 ]
4th Iteration = [ 1, 3, 5 ]

依此类推……最终迭代结果应为空数组 []

需求说明

编写一个循环,每次迭代执行两个操作:

  • 对数组最后一个元素减1
  • 若减1后该元素值为0,将其从数组中弹出

JavaScript 实现示例

let arr = [1, 3, 7, 2];

while (arr.length > 0) {
    // 最后一个元素减1
    arr[arr.length - 1]--;
    // 可选:打印当前迭代后的数组
    console.log(`迭代后数组: [${arr.join(', ')}]`);
    // 元素为0时弹出
    if (arr[arr.length - 1] === 0) {
        arr.pop();
    }
}

逻辑说明

  • 用while循环持续执行,直到数组为空
  • 每次优先修改最后一个元素的值,再判断是否需要移除
  • 若需要查看每一步的迭代结果,可保留console.log语句

内容的提问来源于stack exchange,提问作者valdimar.ein

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 04:20:28