添加2个对象的值

时间:2013-11-18 23:47:26

标签: javascript

水果的价格在对象prices中定义,而水果的库存数量在stocks

问题:您如何找到所有水果的总价值? Usig for.. in,我可以访问stocks中的值,但我无法访问prices的值。

prices = {'appleusd': 1, 'orangeusd': 10};
stocks = {'apple': 100, 'orange': 20};

totalValue = 0;

for (stock in stocks){
    totalValue += stocks[stock] + prices[stock+'usd'];
}

console.log(totalValue);

4 个答案:

答案 0 :(得分:3)

由于pricesstocks中的密钥不同,因此您必须将usd附加到库存密钥才能获得正确的价格。然后,您需要将价格乘以库存数量,并在每次迭代时将结果添加到totalValue

prices = {'appleusd': 1, 'orangeusd': 10};
stocks = {'apple': 100, 'orange': 20};

totalValue = 0;

for (var stock in stocks){
    totalValue += stocks[stock] * prices[stock + 'usd'];
}

console.log(totalValue); // 300

编辑:似乎自从我第一次发布此内容以来,您已经编辑了代码以解决我在这里提出的一些问题。唯一剩下的错误是你的代码将两个值加在一起而不是相乘。

答案 1 :(得分:0)

一个快速的例子:

prices = {'appleusd': 1, 'orangeusd': 10};

sum = 0;
for (var fruit in prices) {
    alert("The fruit " + fruit + " has price " + prices[fruit]);
    sum += prices[fruit];
}

答案 2 :(得分:0)

pricesstocks使用相同的密钥。

prices = {'apple': 1, 'orange': 10};
stocks = {'apple': 100, 'orange': 20};

totalValue = 0;

for (fruit in stocks){
    totalValue += stocks[fruit] * prices[fruit];
}

console.log(totalValue);

答案 3 :(得分:0)

我倾向于将您的收藏分组,以便更有意义:

var stock = {
  apple: {
    quantity: 100,
    priceusd: 1
  },
  orange: {
    quantity: 20,
    priceusd: 10
  }
}

function getTotalValue() {
  var totalValue = 0;
  for (var item in stock) {
    totalValue += stock[item].quantity * stock[item].priceusd;
  }
  return totalValue;
}

var totalValue = getTotalValue();
console.log(totalValue); // 300