【问题标题】:Unable to push to an array that is inside an object无法推送到对象内部的数组
【发布时间】:2019-04-06 21:49:50
【问题描述】:

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

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

【问题讨论】:

  • 看起来知道kitchen 是什么对于理解这个问题非常重要。也许你可以把它贴出来?
  • 很抱歉。
  • var kitchen = [ { belongsTo: "fruits", items: [] }, { belongsTo: "veggies", items: [] } ]
  • 您正试图推入item.items[1]。是item.items 和数组数组吗?
  • 好吧,从技术上讲,我有两个数组。一个属于厨房,另一个属于蔬菜。

标签: javascript arrays object javascript-objects


【解决方案1】:

我刚刚重组了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>

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2019-07-20
      • 2017-09-26
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 2020-04-29
      • 2018-07-20
      • 2020-10-11
      相关资源
      最近更新 更多