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

如何点击按钮将customers数组对象中itemSold和itemGet的值置为null?

解决方案

要实现点击按钮后将customers数组中所有对象的product.itemSold和itemGet数组元素全部置为null,可以按以下方式完善removeProducts函数:

// 初始customers数组示例
let customers = [
  {
    active: true,
    id: 1,
    product: {
      itemSold: [{ name: "Product 1" }, { name: "Product 2" }],
      itemGet: [{ name: "Gift 1" }, { name: "Gift 2" }],
    },
  },
  {
    active: true,
    id: 2,
    product: {
      itemSold: [{ name: "Product 3" }, { name: "Product 4" }],
      itemGet: [{ name: "Gift 3" }, { name: "Gift 4" }],
    },
  },
];

// 绑定按钮点击事件
document.getElementById("clickButton").addEventListener("click", removeProducts);

function removeProducts() {
  // 遍历每个客户对象
  customers.forEach((customer) => {
    // 将itemSold数组的每个元素替换为null
    customer.product.itemSold = customer.product.itemSold.map(() => null);
    // 将itemGet数组的每个元素替换为null
    customer.product.itemGet = customer.product.itemGet.map(() => null);

    // 若需直接修改原数组而非生成新数组,可改用循环:
    // for (let i = 0; i < customer.product.itemSold.length; i++) {
    //   customer.product.itemSold[i] = null;
    // }
    // for (let i = 0; i < customer.product.itemGet.length; i++) {
    //   customer.product.itemGet[i] = null;
    // }
  });

  // 可选:控制台输出验证结果
  console.log(customers);
}

关键逻辑说明

  • 使用forEach遍历customers数组,逐个处理每个客户对象
  • 利用map方法创建新数组,将原数组的每个元素替换为null(这种方式不会改变原数组的引用,若需要保留原数组引用,可使用for循环直接修改元素)
  • 通过addEventListener给目标按钮绑定点击事件,触发函数执行

执行后,customers数组会转换成你指定的结构,所有itemSold和itemGet的元素均为null。

内容的提问来源于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 00:55:31