如何向购物清单函数批量添加多个商品?
问题解决:购物清单函数批量添加商品失效
原代码核心问题
- 数据无法持久:函数内部的
list是局部变量,每次调用函数都会重新初始化,之前添加的商品不会被保留。 - 参数接收限制:函数仅定义了单个参数
x,调用时传入多个参数无法被处理。 - 批量添加逻辑缺失:未遍历传入的所有商品,无法逐个判断是否可添加。
修复方案(基础版)
将购物清单改为全局变量,使用剩余参数接收批量商品,遍历判断逐个添加:
// 全局保存购物清单,确保数据持久 let shoppingList = [["carrots", 3], ["almond milk", 1], ["cauliflower", 10], ["tea", 15]]; function addToShoppingList(...items) { // 遍历所有传入的商品 for (const item of items) { if (shoppingList.length <= 5) { shoppingList.push(item); console.log(`已添加商品: ${item[0]}, 当前清单:`, shoppingList); } else { console.log("The shopping list is full, can not add any other items"); // 清单满后停止添加剩余商品 break; } } } // 调用函数添加多个商品 addToShoppingList(["salmon", 2], ["strawberry", 15]);
进阶优化(闭包封装,避免全局污染)
如果不想使用全局变量,可通过闭包维护购物清单的私有状态:
const createShoppingList = () => { // 闭包内的私有清单,外部无法直接修改 let list = [["carrots", 3], ["almond milk", 1], ["cauliflower", 10], ["tea", 15]]; return (...items) => { for (const item of items) { if (list.length <= 5) { list.push(item); console.log(`已添加商品: ${item[0]}, 当前清单:`, list); } else { console.log("The shopping list is full, can not add any other items"); break; } } }; }; // 创建购物清单实例 const addToShoppingList = createShoppingList(); // 调用添加商品 addToShoppingList(["salmon", 2], ["strawberry", 15]);
内容的提问来源于stack exchange,提问作者Florence
相关产品推荐
相关产品推荐

