JSON API是现代Web开发中最常用的数据交换格式之一,它以轻量级、易读易写的特点被广泛应用于前后端通信。在处理从API检索到的JSON数据时,计算是常见的操作需求。
问题:JSON中的数字被解析为字符串导致计算错误
// 错误示例
const data = { "price": "100", "quantity": "5" };
const total = data.price * data.quantity; // 结果为500,但类型转换不明确
// 正确做法
const total = Number(data.price) * Number(data.quantity);
问题:JSON中某些字段可能缺失或为null
// 解决方案
const total = (data.price || 0) * (data.quantity || 1);
问题:JavaScript中浮点数计算可能产生精度问题
// 错误示例
0.1 + 0.2 === 0.3; // false
// 解决方案
function safeAdd(a, b) {
const multiplier = Math.pow(10, Math.max(getDecimalLength(a), getDecimalLength(b)));
return (a * multiplier + b * multiplier) / multiplier;
}
function getDecimalLength(num) {
const decimal = num.toString().split('.')[1];
return decimal ? decimal.length : 0;
}
问题:处理大型JSON数组时计算性能低下
// 优化方案
const largeData = [...]; // 大型JSON数组
// 使用reduce进行高效聚合
const total = largeData.reduce((sum, item) => {
return sum + (item.value || 0);
}, 0);
const cartItems = [
{ id: 1, name: "商品A", price: 99.99, quantity: 2 },
{ id: 2, name: "商品B", price: 199.99, quantity: 1 }
];
// 计算总价
const subtotal = cartItems.reduce((sum, item) => sum + item.price * item.quantity, 0);
const tax = subtotal * 0.1; // 10%税
const total = subtotal + tax;
const salesData = [
{ month: "Jan", revenue: 15000 },
{ month: "Feb", revenue: 18000 },
// ...其他月份数据
];
// 计算年度总收入和平均月收入
const annualRevenue = salesData.reduce((sum, month) => sum + month.revenue, 0);
const avgMonthlyRevenue = annualRevenue / salesData.length;
function calculateTreeTotal(node) {
if (!node.children || node.children.length === 0) {
return node.value || 0;
}
return node.children.reduce((sum, child) => {
return sum + calculateTreeTotal(child);
}, node.value || 0);
}
const discountRules = [
{ condition: (total) => total > 1000, discount: 0.2 },
{ condition: (total) => total > 500, discount: 0.1 }
];
function applyDiscount(total) {
const applicableRule = discountRules.find(rule => rule.condition(total));
return applicableRule ? total * (1 - applicableRule.discount) : total;
}
通过理解这些基础概念和解决方案,您可以更有效地处理从JSON API检索到的数据并进行各种计算操作。
没有搜到相关的文章