首页 > 解决方案 > 求幂赋值和array.Reduce的问题

问题描述

我正在尝试解决测试。但是当方法 Reduce 给我一个错误的答案时,我遇到了一个问题。在这里我需要检查371 = 3**3 + 7**3 + 1**3 ,我得到了 347,比如3 + 7**3 + 1**3.为什么我在第一次通话时弄错了蓄能器?为什么在这种情况下,当 item * item * item 为真时 Math.pow 是错误的?

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)

标签: javascriptreduce

解决方案


您在 reduce 方法中缺少初始总和值 0。正如这里提到的,

对数组中的每个元素执行的函数(第一个元素除外,如果没有提供 initialValue)。

因此,您必须将初始值传递给 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)


推荐阅读