javascript - 求幂赋值和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)
解决方案
您在 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)
推荐阅读
- django - Django 忽略 500 个错误
- reactjs - 坐标更改后自定义标记不重新渲染
- amazon-web-services - AWS网关许多API路由到单个lambda集成每个端点映射到不同的Lambda函数(java)
- html - 如果内容太小,使 html 页面至少占用 100% 的视口
- javascript - 这个算法如何对抗计数排序?
- sql - 为每个唯一 ID 选择最近 30 个日期
- django - 尝试 pip install psycopg2==2.7 时出错。*
- java - 两边挑?
- google-app-engine - Cloud Build 无法构建 App Engine Python 3.8 应用(由于 pip 错误?)
- node.js - AWS Lambda (Node.js) 监控网站是否在线