js实现总计
实现总计功能的方法
在JavaScript中实现总计功能通常涉及对数组中的数值进行累加或对特定属性进行求和。以下是几种常见场景的实现方式。
数组元素求和
对普通数值数组进行总计,可以使用reduce方法:
const numbers = [1, 2, 3, 4, 5];
const total = numbers.reduce((sum, current) => sum + current, 0);
console.log(total); // 输出15
对象属性求和
当数组包含对象且需要对特定属性求和时:
const items = [
{ price: 10, quantity: 2 },
{ price: 5, quantity: 4 },
{ price: 8, quantity: 1 }
];
const totalPrice = items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
console.log(totalPrice); // 输出38
动态DOM元素求和
在网页中对动态生成的输入框数值进行实时总计:
document.querySelectorAll('.price-input').forEach(input => {
input.addEventListener('input', () => {
const prices = Array.from(document.querySelectorAll('.price-input'))
.map(input => parseFloat(input.value) || 0);
document.getElementById('total').textContent =
prices.reduce((sum, price) => sum + price, 0);
});
});
带条件筛选的求和
仅对满足条件的元素进行总计:
const transactions = [
{ amount: 100, type: 'income' },
{ amount: 50, type: 'expense' },
{ amount: 200, type: 'income' }
];
const incomeTotal = transactions
.filter(t => t.type === 'income')
.reduce((sum, t) => sum + t.amount, 0);
console.log(incomeTotal); // 输出300
格式化输出结果
对总计结果进行货币格式化:
const total = 1234.56;
const formattedTotal = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
}).format(total);
console.log(formattedTotal); // 输出"$1,234.56"
这些方法覆盖了从基础数组操作到实际业务场景的应用,可根据具体需求选择合适的方式实现总计功能。







