【发布时间】:2021-12-26 21:23:04
【问题描述】:
我刚开始学习reduce方法,陷入了这个问题......
N answer
123 6
987 24
例如 9 + 8 + 7 = 24,但参数是数字。
这是我尝试过的:
function solution (n){
let result = new Array (n)
let answer = result.reduce((a,b) => {
return a + b
})
}
这是我的代码,但我收到了TypeError [Error]: Reduce of empty array with no initial value
【问题讨论】:
-
您实例化了一个大小为 n 的空数组。它不包含任何东西。您输入的是一个字符串,因此将其转换为 char n.split('') 或 [...n] 或 Array.from(n) 的数组,然后您可以映射到 int 并使用您的 reduce 操作
-
这能回答你的问题吗? How to find the sum of an array of numbers
-
这个->
(''+123).split('').reduce((acc,n)=>acc+=parseInt(n),0);
标签: javascript reduce