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

如何向购物清单函数批量添加多个商品?

问题解决:购物清单函数批量添加商品失效

原代码核心问题

  • 数据无法持久:函数内部的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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 10:01:13