【问题标题】:Trouble accessing object within an object (for a for loop)无法访问对象内的对象(对于 for 循环)
【发布时间】:2017-12-29 06:38:50
【问题描述】:

基本上,我正在尝试创建一个 for 循环,该循环创建一个包含每个糖果名称和价格的对象。我可以毫无问题地访问某天的库存

console.log(store3[4]['inventory sold'])

{ 'Dark Chocolate Crunchies': { cost: 4.29, quantity: 2 },
  'Mint Wafers': { cost: 1.09, quantity: 1 },
  'Peppermint Poppers': { cost: 2.38, quantity: 0 },
  'Peanut Butter Buttered Peanuts': { cost: 1.79, quantity: 2 },
  'Berry Bites': { cost: 7.89, quantity: 5 },
  'Caramel Twists': { cost: 0.5, quantity: 7 },
  'Banana Bunches': { cost: 4.53, quantity: 2 } }

还有这个

console.log(store3[4]['inventory sold']['Mint Wafers'])

{ cost: 1.09, quantity: 1 }

但是,对于 for 循环,我需要使用数值,并且由于某种原因,当我尝试以这种格式运行先前的命令时,我得到未定义。有什么建议吗?

console.log(store3[4]['inventory sold'][1])

undefined

【问题讨论】:

    标签: javascript object for-loop reference javascript-objects


    【解决方案1】:

    您可以使用 Object.keys 仅获取一个键数组,然后在该数组上使用 forEach,您将能够访问对象的每个属性。

    var datas = { 
      'Dark Chocolate Crunchies': { cost: 4.29, quantity: 2 },
      'Mint Wafers': { cost: 1.09, quantity: 1 },
      'Peppermint Poppers': { cost: 2.38, quantity: 0 },
      'Peanut Butter Buttered Peanuts': { cost: 1.79, quantity: 2 },
      'Berry Bites': { cost: 7.89, quantity: 5 },
      'Caramel Twists': { cost: 0.5, quantity: 7 },
      'Banana Bunches': { cost: 4.53, quantity: 2 }
    }
    
    
    Object.keys(datas).forEach(function (key) {
      console.log(key) ;
      console.log('cost',datas[key]['cost']) ;
      console.log('quantity',datas[key]['quantity']) ;
    }) ;

    【讨论】:

    • 谢谢!这非常有帮助
    猜你喜欢
    • 1970-01-01
    • 2020-07-25
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 1970-01-01
    • 2015-06-07
    • 2012-02-29
    • 1970-01-01
    相关资源
    最近更新 更多