【发布时间】:2021-04-01 15:43:00
【问题描述】:
我有一个包含两个对象的简单数组,我需要在其中获取 1 个月的产品价格。
数组可以包含 2 或 3 个项目,所以我正在检查它是 2 还是 3。然后我将对象存储在它们自己的变量中,并使用这些变量的参数值调用函数 getOneMonthPrice。
函数getOneMOnthPrice 循环遍历产品并检查months 属性是否为01 month 的值,如果是则返回价格。
但现在我只是未定义,而如果我在函数中使用 console.log,我可以看到控制台中显示的值。
这里出了什么问题?
请注意,我实际上已经从我正在处理的实际项目中删除了大部分代码。这只是最短的版本。如果可以的话,请给我一个基于这种格式的解决方案。
这是sn-p:
const arr = [{
"name": "Boom Boom Ltd.",
"products": [{
"price": "3.33",
"months": "24 months"
},
{
"price": "10.95",
"months": "01 month"
}
]
},
{
"name": "Bam Bam Ltd.",
"products": [{
"price": "5.93",
"months": "24 months"
},
{
"price": "12.95",
"months": "01 month"
}
]
}
];
function getOneMonthPrice(company) {
company.products.forEach(item => {
if (item.months === "01 month") {
return item.price;
}
});
};
if (arr.length === 2) {
const company1 = arr[0];
const company2 = arr[1];
console.log(getOneMonthPrice(company1));
}
【问题讨论】:
标签: javascript jquery