【问题标题】:Javascript Array.reduce() breaking the page with Error Code 6Javascript Array.reduce() 使用错误代码 6 破坏页面
【发布时间】:2021-02-05 14:39:50
【问题描述】:

只要我不传递初始值,网页就可以正常工作,但在这种情况下,它只会给我 TypeError,因为当只有最后一个元素时(如预期的那样)。这就是为什么我试图将 0 作为初始值传递给 reduce 函数(sn-p 下面的第 4 行)。但是一旦我这样做,它就会破坏整个页面并显示错误代码 6。

我想要达到的目标: 我将数组中所有元素的总和相加,然后将该总和推送到另一个数组,删除第一个元素并重复该过程。当没有剩余元素时,我想从 reduce() 函数返回 0,这就是我尝试传递初始值 (0) 的原因。

function partsSums(ls) {
  let sumArr = [];
  while (ls.length >= 0) {
    sumArr.push(ls.reduce((acc, cur) => acc + cur, 0));
    ls.shift();
  }
  return sumArr;
}

partsSums([0, 1, 3, 6, 10]);

我正在寻找的输出是:[20, 20, 19, 16, 10, 0]

【问题讨论】:

  • ls.length >= 0 更改为ls.length > 0。 while 循环的条件永远不会为 false,因为数组的长度永远不会低于 0,所以你有一个无限循环。
  • 您要查找的输出是什么?
  • 当我调用 reduce() fn 的 ls 数组中没有剩余元素时,我想将 0 推送到我的 sumArr 中。如果我将 ls.length 设置为 >0,那么它会在最后一个元素之后停止。我可以在 reduce() fn 之后推 0,但是有什么办法可以在 reduce 函数中做到这一点?
  • 我要找的输出是:[20, 20, 19, 16, 10, 0]
  • @Link 你可以在while循环之后添加sumArr.push(0)

标签: javascript arrays reduce array.prototype.map


【解决方案1】:

正如 cmets 中提到的,您将获得一个无限循环,因为数组的长度永远不会低于 0

如其他答案所示,您可以通过将条件更改为ls.length > 0 来解决该问题,但是当数组为空时,您不会在最终迭代中将0 推入结果中。

不要在while() 条件下测试长度,而是在调用reduce() 之后测试它,然后跳出循环。

function partsSums(ls) {
  let sumArr = [];
  while (true) {
    sumArr.push(ls.reduce((acc, cur) => acc + cur, 0));
    if (ls.length == 0) {
      break;
    }
    ls.shift();
  }
  return sumArr;
}

console.log(partsSums([0, 1, 3, 6, 10]));

【讨论】:

    【解决方案2】:

    你可以这样做:

    function partsSums(ls)
      {
      let sumArr = []
        , lng    = ls.length
        ;
      while ( lng >= 0)
        {
        sumArr.push(ls.reduce((acc, cur) => acc + cur, 0))
        ls.shift()
        --lng
        }
      return sumArr
      }
    
    console.log(JSON.stringify( partsSums([0, 1, 3, 6, 10])  ))
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

    • 谢谢!这正是我一直在寻找的。我也应该减少长度。我的错。非常感谢@Mister Jojo
    【解决方案3】:

    您的代码的问题是条件ls.length >= 0。这种情况会导致您进入无限循环。改成ls.length > 0

    建议

    您似乎正在寻求从右到左的累积总和。但是你的功能并不划算。你可以使用suffix-sum来解决这个问题。

    const suffixSum = arr => {
      const res = [];
      const {length} = arr;
      res[length] = 0;
    
      for (let i = length - 1; i >= 0; i--) {
        res[i] = res[i+1] + arr[i];
      }
      
      return res;
    }
    
    console.log(suffixSum([0, 1, 3, 6, 10]));

    此算法需要O(n) 时间,而您的算法需要O(n^2) 时间。

    【讨论】:

    • 感谢您的回答,但我只是想了解如何使用 Array.prototype.reduce() fn。你的意思是说我的网页崩溃是因为我的功能不划算?
    • 不!您的问题的解决方案在于 cmets 部分。只是因为ls.length >= 0。它迫使你进入一个无限循环。
    • 我只是为你的问题的第二部分分享一个很好的解决方案我想要实现的目标
    • 谢谢,但这仍然不能解决我的问题,因为我想在返回结果数组的末尾添加 0,并尝试在 Array.prototype.reduce( ) 函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 2022-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多