[英]Can someone explain this for/in loop to me?
/*
Write each function according to the instructions.
When a function's parameters reference `cart`, it references an object that looks like the one that follows.
{
"Gold Round Sunglasses": { quantity: 1, priceInCents: 1000 },
"Pink Bucket Hat": { quantity: 2, priceInCents: 1260 }
}
*/
function calculateCartTotal(cart) {
let total = 0;
for (const item in cart){
let quantity = Object.values(cart[item])[0];
let price = Object.values(cart[item])[1];
total += price * quantity;
}
return total;
}
function printCartInventory(cart) {
let inventory = "";
for (const item in cart){
inventory += `${Object.values(cart[item])[0]}x${item}\n`;
}
return inventory;
}
module.exports = {
calculateCartTotal,
printCartInventory,
};
让我困惑的部分是函数 calculateCartTotal。 我感到困惑的是,这个循环如何知道获取 priceInCents? 例如,如果我要在名为“重量:24”的对象中添加另一个值,假设它是 24 克,那么对象值如何跳过数量和重量而只获取 priceInCents? 希望我能理解我的困惑,并且有人可以为我解释!
如果您尝试运行以下程序,那么您将更容易可视化所有内容。
发生的事情是 item 只是元素的索引,对于一个对象,我们可以使用键名来访问它的值或它的索引。
您可以阅读此文档以了解Object.values()
的作用。
function calculateCartTotal(cart) {
let total = 0;
for (const item in cart) {
console.log(item)
let quantity = Object.values(cart[item])[0];
let price = Object.values(cart[item])[1];
total += price * quantity;
}
return total;
}
var cart = [
{
quantity: 2,
price: 5,
weight: 24
},
{
quantity: 3,
price: 10,
weight: 90
},
{
quantity: 7,
price: 20,
weight: 45
},
{
quantity: 1,
price: 100,
weight: 67
}
]
console.log(calculateCartTotal(cart))
输出:
0
1
2
3
280
程序 2 演示正在发生的事情
function calculateCartTotal(cart) {
console.log(Object.values(cart[2])[1])
console.log(cart[2]['price'])
console.log(cart[2].price)
}
var cart = [
{
quantity: 2,
price: 5,
weight: 24
},
{
quantity: 3,
price: 10,
weight: 90
},
{
quantity: 7,
price: 20,
weight: 45
},
{
quantity: 1,
price: 100,
weight: 67
}
]
calculateCartTotal(cart)
输出:
20
20
20
我是迪帕克,🙂
我可以解释(程序2演示)。 见我的朋友,你将能够看到第一个console.log,即console.log(Object.values(cart[2])[1])... 所以,object 表示整个购物车,.values 表示唯一特定对象包含的数字。 现在,看看结果,即 20。那么,这 20 是怎么来的?... 现在,看看我之前写的 console.log。 在 [2] 的 .value 购物车的括号中(这意味着 2 是该购物车的位置,这就是为什么它被写为购物车 [2] 即在购物车第二位置的对象内和购物车 [2] 之后这个数字是否存在 [1],这意味着在第二个位置的对象内,即,
下面的对象:- 对象的位置 var cart = [
quantity: 2, 0 position
price: 5,
weight: 24
},
{
quantity: 3, 1 position
price: 10,
weight: 90
},
{
quantity: 7, 2 position
price: 20,
weight: 45
} ,
{
quantity: 1, 3 position
price: 100,
weight: 67
}
]
console.log(计算CartTotal(购物车))
现在,匹配console.log。
它说 console.log(OBJECT.values(cart[2])[1]);
在购物车中,查看第二个位置的对象,即
{数量:7,2仓价格:20,重量:45}
因此,cart[2] 表示您将在上面的整个对象。 [1] 表示对象内部从 0 开始计数位置。 所以,在
values
0位置数量,7,
1个仓位价格,20个,2个仓位权重。 45.
[1] 仓位价格:20。
所以,cart[2] 表示 {数量:7,2 位置价格:20,重量:45}
并且,[1] 表示价格:20。
所以,你的答案是 20。
注意:方括号内的数字将给出对象的位置或对象内部的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.