You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用.reduce()方法进行乘除运算时遇到问题

解决.reduce()计算器乘法为0、除法为Infinity的问题

问题根源

你的核心问题出在输入逻辑的do-while循环:当你输入0终止输入时,程序会先把这个0添加到datosObtenidos数组里,再退出循环。这个额外的0直接导致了乘法结果为0(任何数乘0都得0),以及除法结果为Infinity(最后一步会除以这个0)。

两种修复方案

方案1:输入时直接过滤终止用的0

修改introducirNum的循环逻辑,只把非0的数加入数组,输入0时仅触发循环终止:

const introducirNum = () => {
  let datosObtenidos = [];
  let datos;
  do {
    datos = Number(prompt('Introduce un número.'));
    if (isNaN(datos)) {
      alert('Debes introducir solo números NO letras.');
      return introducirNum();
    } else if (datos !== 0) { // 仅添加非0数值
      datosObtenidos.push(datos);
    }
  } while (datos !== 0)
  return datosObtenidos
}

这种方式从根源避免了0进入数组,最直接有效。

方案2:获取数组后移除末尾的0

如果不想改动输入逻辑,可以在拿到输入数组后,用pop()删掉最后那个用于终止输入的0,同时处理用户只输入0的边界情况:

numerosIntroducidos = introducirNum();
// 移除末尾的0,同时确保数组不会被删空
if (numerosIntroducidos.length > 0) {
  numerosIntroducidos.pop();
}

额外优化建议

你的乘法reduce可以加上初始值1,让逻辑更严谨(避免数组长度为1时的潜在问题):

const multiplicacion = numerosIntroducidos.reduce((valorInicial, segundoValor) => valorInicial * segundoValor, 1);

内容的提问来源于stack exchange,提问作者Gomet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 19:55:19