无法推送到对象内部的数组

时间:2019-04-06 21:49:50

标签: javascript arrays object javascript-objects

我正在尝试将某些东西压入驻留在对象内部的数组中。事情是它在运行,但是当我查看该对象时,即使我将其推入,该数组仍为空。

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);
    });
}

2 个答案:

答案 0 :(得分:0)

我只是重组了<div id="myDiv"> <p> This is the first paragraph tag in the div.</p> <p> I will try to loop through this div tag.</p> <p> In order to get all of the elements used.</p> <p> As well as the text in this div.</p> </div>对象,因此您不必每次都循环以添加项目。

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})`);
    });
  });
}

答案 1 :(得分: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();