我无法向浏览器显示对象内部数组元素的总和。
这是我的 JavaScript 代码:
const products = {
productName: [],
description: [],
quantity: [],
unitOfMeasure: []
}
let countLog = products.quantity;`
function sumArray(sum) {
let displaySumEl = document.getElementById('display-sum');
sum = countLog.reduce((total, item) => total + item);
displaySumEl.textContent = `Total: `;
displaySumEl.textContent += `${parseInt(sum)}`;
console.log(countLog);
}
这里的问题是 sum 变量只显示数组中的数字,而不是 countLog 变量中数字的总和。
function sumArray(sum) {
let displaySumEl = document.getElementById('display-sum');
sum = countLog.reduce((total, item) => total + item, 0);
displaySumEl.textContent = `Total: ${sum}`;
console.log(countLog);}
reduce 函数采用第二个参数作为总计的初始值