无法推送到对象内的数组

问题描述 投票:0回答:2

我正在尝试将一些东西放入一个存在于我的对象中的数组中。事情是它运行,但是当我查看对象时,即使我进入,数组仍然是空的。

function add(){
    addItem = prompt("Where would you like to add this item to?")

    kitchen.forEach(function(item){
        if (addItem == item.belongsTo["fruits"]) {
            itemAdded = prompt("What would you like to add?");
            item.items[0].push(itemAdded);
        }else if(addItem == item.belongsTo["veggies"]){
            itemAdded = prompt("What would you like to add?");
            item.items[1].push(itemAdded);
        }
    });
}

function showKitchen(){
    kitchen.forEach(function(list){
        console.log(list);
    });
}

javascript arrays object javascript-objects
2个回答
0
投票

我只是重新组织了kitchen对象,这样你就不需要每次都循环来添加一个项目。

// persist items with count
const kitchen = {
  fruits: {},
  veggies: {}
};

function addItemToKitchen() {
  const group = prompt("Where would you like to add this item to?");
  if (group) {
    const itemToAdd = prompt(`What would you like to add in kitchen(${group}?`);

    if (itemToAdd) {
      // pick the group if found or create one
      kitchen[group] = kitchen[group] || {};
      // add item to group
      kitchen[group][itemToAdd] = (kitchen[group][itemToAdd] || 0) + 1;

      showKitchen();
    }
  }
}

function showKitchen() {
  Object.entries(kitchen).forEach(([group, items]) => {
    console.log(group, ':');
    Object.entries(items).forEach(([item, count]) => {
      console.log(`\t${item}(${count})`);
    });
  });
}
<button onclick="addItemToKitchen()">Add Item</button>
<button onclick="showKitchen()">Show Kitchen List</button>

0
投票

  var kitchen = [ 
    { belongsTo: "fruits", items: [] },
    { belongsTo: "veggies", items: [] } 
    ]
    
  function add(){
    var addItem = prompt("Where would you like to add this item to?");
    if(addItem == "fruits"){
      var item = prompt("What would you like to add?");
      kitchen[0].items.push(item);
    }
    else if(addItem == "veggies"){
      var item = prompt("What would you like to add?");
      kitchen[1].items.push(item);
    }
    // console.log(kitchen);
    showKitchen();
  };

  function showKitchen(){
    kitchen.forEach(function(list){
        console.log(list);
    });
}
add();
© www.soinside.com 2019 - 2024. All rights reserved.