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

如何在添加元素后使用break?实现数组元素为null时添加元素并终止循环

解决方案

要实现需求,我们需要先判断当前遍历到的customer对象下product.itemSold数组的所有元素是否均为null,满足条件时添加'car'并终止循环。补充后的完整代码如下:

let customer = [{
    active: true,
    product: {
      itemSold: [null, null],
      purchasedItems: []
    },
  },
  {
    active: true,
    product: {
      itemSold: [null, null],
      purchasedItems: []
    },
  },
];

let itemSold = ["car", "home"];
let purchasedItems = ["phone", "computer"];

for (let i = 0; i < customer.length; i++) {
  // 检查itemSold数组的所有元素是否都是null
  const allItemsNull = customer[i].product.itemSold.every(item => item === null);
  
  if (allItemsNull) {
    // 向itemSold数组添加'car'
    customer[i].product.itemSold.push('car');
    // 终止循环
    break;
  }
}

// 可通过以下代码验证结果
// console.log(customer[0].product.itemSold); // 输出: [null, null, 'car']

关键逻辑说明

  • 用Array.every()方法遍历itemSold数组,确认每一个元素都是null,返回布尔值作为判断条件。
  • 满足条件时,调用Array.push()添加目标元素,再执行break跳出整个循环,仅处理第一个符合要求的customer对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 13:15:27