如何点击按钮将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
相关产品推荐
相关产品推荐

