好的,如果我有这个:
var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];
我想要的是求和:
1 + 2 + 3 && 1 + 4 + 7 && 1 + 5 + 9
就像在井字游戏中一样,所以我的问题是如何在不使用 300 行代码填充我的代码的情况下做到这一点?
最佳答案
您可以取两个数组,其起始值为行和列,并将总和作为索引来计算所需的总和。
15 / 1 2 3 | 6 4 5 6 | 15 7 8 9 | 24 --- --- --- \ 12 15 18 15
var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9"],
rows = [0, 3, 6].map(i => [0, 1, 2].reduce((s, j) => s + +array[i + j], 0)),
cols = [0, 1, 2].map(i => [0, 3, 6].reduce((s, j) => s + +array[i + j], 0)),
slash = [0, 4, 8].reduce((s, i) => s + +array[i], 0),
backslash = [2, 4, 6].reduce((s, i) => s + +array[i], 0);
console.log(rows); // -
console.log(cols); // |
console.log(slash); // /
console.log(backslash); // \
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 如何检查js中每一行的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48252513/