js实现小计
实现小计功能
在JavaScript中实现小计功能通常涉及对一组数据进行累加或汇总。以下是几种常见场景的实现方法:
数组元素求和
const numbers = [1, 2, 3, 4, 5];
const subtotal = numbers.reduce((sum, num) => sum + num, 0);
console.log(subtotal); // 输出15
表格行小计
假设有一个HTML表格,需要计算每行的小计:
<table id="order-table">
<tr>
<td><input type="number" class="quantity" value="2"></td>
<td><input type="number" class="price" value="10"></td>
<td class="subtotal">20</td>
</tr>
<tr>
<td><input type="number" class="quantity" value="3"></td>
<td><input type="number" class="price" value="5"></td>
<td class="subtotal">15</td>
</tr>
</table>
<p>总计: <span id="total">0</span></p>
function calculateSubtotals() {
const rows = document.querySelectorAll('#order-table tr');
let grandTotal = 0;
rows.forEach(row => {
const quantity = parseFloat(row.querySelector('.quantity').value) || 0;
const price = parseFloat(row.querySelector('.price').value) || 0;
const subtotal = quantity * price;
row.querySelector('.subtotal').textContent = subtotal.toFixed(2);
grandTotal += subtotal;
});
document.getElementById('total').textContent = grandTotal.toFixed(2);
}
// 监听输入变化
document.querySelectorAll('#order-table input').forEach(input => {
input.addEventListener('change', calculateSubtotals);
});
// 初始计算
calculateSubtotals();
对象数组属性汇总
处理包含多个对象的数组时,可以这样计算小计:
const items = [
{ name: 'Item1', quantity: 2, price: 10 },
{ name: 'Item2', quantity: 1, price: 20 },
{ name: 'Item3', quantity: 3, price: 5 }
];
const subtotals = items.map(item => ({
...item,
subtotal: item.quantity * item.price
}));
const grandTotal = subtotals.reduce((sum, item) => sum + item.subtotal, 0);
console.log(subtotals, grandTotal);
动态添加项目的小计
对于动态添加的项目,可以使用事件委托来处理计算:

document.getElementById('item-container').addEventListener('input', (e) => {
if (e.target.classList.contains('quantity') || e.target.classList.contains('price')) {
const row = e.target.closest('.item-row');
const quantity = parseFloat(row.querySelector('.quantity').value) || 0;
const price = parseFloat(row.querySelector('.price').value) || 0;
row.querySelector('.subtotal').textContent = (quantity * price).toFixed(2);
updateGrandTotal();
}
});
function updateGrandTotal() {
const subtotals = Array.from(document.querySelectorAll('.subtotal'));
const total = subtotals.reduce((sum, el) => sum + parseFloat(el.textContent), 0);
document.getElementById('grand-total').textContent = total.toFixed(2);
}
这些方法涵盖了JavaScript中实现小计功能的常见场景,可以根据具体需求选择或组合使用。






