【问题标题】:How to add multiple items to a function如何将多个项目添加到函数中
【发布时间】:2022-11-12 07:19:35
【问题描述】:

我正在创建一个购物清单函数,每次我将一个项目放在函数括号中时,它都会自动添加到购物清单数组中。如果数组中的项目数小于或等于 5 个项目,那就很好了。否则,一旦商品数量超过 5 个,它会打印“购物清单已满,不能添加任何其他商品”。

在这种情况下,我尝试调用该函数并一次添加多个项目,但它不起作用。我该如何解决这个问题?你的帮助对我来说意味着整个世界!感谢你们。

这是我的代码:

var x;
function shoppingListofTheWeek(x){
    var list = [["carrots", 3], ["almond milk", 1], ["cauliflower", 10], ["tea", 15]]
    
    if (list.length <= 5) {
        list.push(x);
        console.log(list);
    } else {
        console.log("The shopping list is full, can not add any other items in the cart.");
    }
}

shoppingListofTheWeek(["salmond", 2],["strawberry",15]);

【问题讨论】:

    标签: javascript function multidimensional-array


    【解决方案1】:

    该函数可以使用省略号获取多个参数,然后循环遍历它们。

    var x;
    
    function shoppingListofTheWeek(...items) {
      var list = [
        ["carrots", 3],
        ["almond milk", 1],
        ["cauliflower", 10],
        ["tea", 15]
      ]
      items.forEach(x => {
        if (list.length <= 5) {
          list.push(x);
          console.log(list);
        } else {
          console.log("The shopping list is full, can not add any other items in the cart.");
        }
      });
    }
    
    shoppingListofTheWeek(["salmond", 2], ["strawberry", 15]);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-05
      • 1970-01-01
      • 1970-01-01
      • 2019-11-25
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      • 2020-05-02
      相关资源
      最近更新 更多