幂赋值和数组的问题.减少



我正在尝试解决一个测试。但当Reduce方法给我一个错误的答案时,我遇到了一个问题。这里我需要检查371 = 3**3 + 7**3 + 1**3,我得到了347,就像3 + 7**3 + 1**3.一样。为什么我在第一次调用中得到了错误的累加器?为什么在这种情况下,当item*item*item为true时,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)

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)

最新更新