[英]Adding up the values of 2 objects
水果的價格定義為目標prices
,而水果的庫存量為庫存stocks
。
問題:您如何找到所有水果的總價值? 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);
由於在prices
和stocks
中找到的密鑰不同,因此必須將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
編輯:看來,自從我第一次發布此內容以來,您已經編輯了代碼以解決我在這里提出的一些問題。 唯一剩下的錯誤是您的代碼將兩個值相加而不是相乘。
一個簡單的例子:
prices = {'appleusd': 1, 'orangeusd': 10};
sum = 0;
for (var fruit in prices) {
alert("The fruit " + fruit + " has price " + prices[fruit]);
sum += prices[fruit];
}
對prices
和stocks
使用相同的密鑰。
prices = {'apple': 1, 'orange': 10};
stocks = {'apple': 100, 'orange': 20};
totalValue = 0;
for (fruit in stocks){
totalValue += stocks[fruit] * prices[fruit];
}
console.log(totalValue);
我傾向於將您的收藏歸類,這樣才更有意義:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.