求幂分配问题和 array.Reduce

Problem with Exponentiation assignment and array.Reduce

我正在尝试解决一个测试。但是当 Reduce 方法给我一个错误的答案时,我遇到了一个问题。 在这里,我需要检查 371 = 3**3 + 7**3 + 1**3,我得到了 347,就像 3 + 7**3 + 1**3. 为什么我在第一次调用时得到错误的累加器?为什么在这种情况下 Math.pow 是错误的,而 item * item * item 是正确的?

function narcissistic(value) {
  let array = value
    .toString()
    .split("")
    .map((item) => parseInt(item));
  console.log(array); // [a, b, c, d, ... ]
  const length = array.length;

  let result = array.reduce((sum, item) => {
    return Math.pow(item, length) + sum;
  }); // [a**length + b**length + c**length + ....]
  console.log(result);

  return value == result;
}

narcissistic(371)

您在 reduce 方法中缺少初始总和值 0。 正如here

中提到的

A function to execute on each element in the array (except for the first, if no initialValue is supplied).

因此您必须将初始值传递给 reduce 方法,以便它对每个项目(包括第一个项目)执行给定的方法。

function narcissistic(value) {
  let array = value
    .toString()
    .split("")
    .map((item) => parseInt(item));
  console.log(array); // [a, b, c, d, ... ]
  const length = array.length;

  let result = array.reduce((sum, item) => {
    return Math.pow(item, length) + sum;
  }, 0); // 0 should be the initial sum
  console.log(result);

  return value == result;
}

narcissistic(371)