【发布时间】:2021-03-27 23:04:39
【问题描述】:
我正在尝试解决一个简单的问题:给定一个二维整数数组(由整数组成的数组组成的数组)计算整数的总和。
例如,给定这个二维数组:
[
[1, 0, 0],
[1, 1, 0],
[1, 1, 1]
]
输出将是6。
这是我尝试过的:
const array = [
[1, 0, 0],
[1, 1, 0],
[1, 1, 1]
]
const twoDsum = a => a.reduce( (r,x) => r + x.reduce( (s,y) => s + y) );
console.log(twoDsum(array));
如你所见,我得到了三个整数,这对我来说是无稽之谈。
我还尝试了以下代码来弄清楚发生了什么,但我不明白
const array = [
[1, 0, 0],
[1, 1, 0],
[1, 1, 1]
]
// this function works as you can see from the logs
const sum = a => a.reduce( (r,x) => r + x );
for(let i = 0; i < array.length; i++) {
console.log(sum(array[i]));
}
// I don't get why this doesn't
const twoDsum = a => a.reduce( (r,x) => r + sum(x) );
console.log(twoDsum(array));
【问题讨论】:
-
a.reduce( (r,x) => r + sum(x) )缺少初始值0,因此使用[1, 0, 0]。因此,第一次迭代执行[1, 0, 0] + sum([1, 1, 0]),产生一个字符串。阅读documentation。我建议始终提供一个初始值。
标签: javascript multidimensional-array reduce