**已关闭。**此问题需要debugging details。目前不接受回答。
编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将帮助其他人回答问题。
2天前关闭。
Improve this question的
我不能向浏览器显示对象内部数组元素的总和。
下面是我的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变量中的数字之和。
2条答案
按热度按时间ruarlubt1#
字符串
reduce函数采用第二个参数作为total的初始值
brtdzjyr2#
提供的代码试图使用
reduce()
方法对products.quantity
数组的元素求和,但数量数组中似乎没有值。如果您有一个空数组,reduce()
函数将抛出错误。若要修复此问题,请在调用
reduce()
函数之前确保数量数组中有值。如果数组可能为空,请为reduce()
函数提供初始值以避免错误。下面是
sumArray
函数的修改版本:字符串
在这个修改后的函数中,
reduce()
以初始值0开始。如果countLog
是一个空数组,reduce()
将返回这个初始值,并且不会抛出错误。记住在用数字填充
products.quantity
数组之后调用sumArray()
函数。