Browse Source

feat: 实现相同规格计算平均价格功能

pull/19/head
徐飞洋 1 month ago
parent
commit
3ccade40d3
  1. 39
      pages/evaluate1/index.js

39
pages/evaluate1/index.js

@ -150,8 +150,11 @@ Page({
// 只有当价格不为空时才添加该规格 // 只有当价格不为空时才添加该规格
if (matchedPrice) { if (matchedPrice) {
// 直接使用商品的原始价格,不做任何处理 // 收集相同规格的所有价格,以便计算平均值
specPriceMap[spec] = matchedPrice; if (!specPriceMap[spec]) {
specPriceMap[spec] = [];
}
specPriceMap[spec].push(matchedPrice);
} else { } else {
console.log(`规格'${spec}' 价格为空,不添加`); console.log(`规格'${spec}' 价格为空,不添加`);
} }
@ -160,10 +163,32 @@ Page({
} }
}); });
// 计算每个规格的平均价格
const specAvgPriceMap = {};
Object.keys(specPriceMap).forEach(spec => {
const prices = specPriceMap[spec];
// 过滤掉非数字价格
const validPrices = prices.filter(price => !isNaN(parseFloat(price)));
if (validPrices.length > 0) {
// 计算平均价格
const sum = validPrices.reduce((acc, price) => acc + parseFloat(price), 0);
const avgPrice = sum / validPrices.length;
specAvgPriceMap[spec] = avgPrice.toFixed(2);
console.log(`规格'${spec}' 的平均价格: ${specAvgPriceMap[spec]} (基于 ${validPrices.length} 个价格)`);
} else {
// 如果没有有效价格,使用第一个价格(可能是非数字)
specAvgPriceMap[spec] = prices[0] || '';
console.log(`规格'${spec}' 没有有效价格,使用: ${specAvgPriceMap[spec]}`);
}
});
console.log('规格平均价格映射:', specAvgPriceMap);
console.log('规格价格映射:', specPriceMap); console.log('规格价格映射:', specPriceMap);
// 检查specPriceMap是否为空 // 检查specAvgPriceMap是否为空
if (Object.keys(specPriceMap).length === 0) { if (Object.keys(specAvgPriceMap).length === 0) {
console.error('未提取到有效规格'); console.error('未提取到有效规格');
this.setData({ this.setData({
error: '未提取到有效规格', error: '未提取到有效规格',
@ -173,9 +198,9 @@ Page({
} }
// 转换为规格对象数组 // 转换为规格对象数组
const specifications = Object.keys(specPriceMap).map(spec => { const specifications = Object.keys(specAvgPriceMap).map(spec => {
const price = specPriceMap[spec]; const price = specAvgPriceMap[spec];
console.log(`最终规格'${spec}' 对应价格: '${price}'`); console.log(`最终规格'${spec}' 对应平均价格: '${price}'`);
// 解析规格 // 解析规格
const specInfo = this.parseSpecification(spec); const specInfo = this.parseSpecification(spec);

Loading…
Cancel
Save