javascript - 请我希望在我的 javascript 数组上使用 reduce 方法
问题描述
我有一个总数组,里面有其他值数组。我希望在 forEach 和 reduce() 的帮助下添加嵌套值
// My main array
Total = [
[ 1, 0, 1, 0 ],
[ 0, 1, 0, 0 ],
[ 1, 0, 0, 1 ],
[ 0, 0, 1, 0 ],
[ 0, 1, 0, 0 ],
[ 1, 0, 0, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ] ]
// The code I have
Total.forEach(function(element) {
element.reduce(function(a,b) {
console.log(a+b)
}, 0)
})
// Output not as expected!
1
NaNNaNNaN0 NaNNaNNaN1 NaNNaNNaN0 NaNNaNNaN0 NaNNaNNaN1 []
例如,我想要的是,第一个 forEach 应该给出1+0+1+0 = 2...
等的总和
解决方案
你可以试试这段代码
var Total = [
[ 1, 0, 1, 0 ],
[ 0, 1, 0, 0 ],
[ 1, 0, 0, 1 ],
[ 0, 0, 1, 0 ],
[ 0, 1, 0, 0 ],
[ 1, 0, 0, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ] ];
function myFunction(){
for(let i=0 ;i<Total.length;i++){
console.log(Total[i].reduce(getSum));
}
}
function getSum(total, num) {
return total + num;
}
myFunction();
希望这可以帮助
推荐阅读
- docker - 非root docker权限来来去去
- python - 如何使用 BeautifulSoup 从网站获取 var 脚本中的 json 数据?
- c# - C#如果datagridview中字符单元格值的条件
- javascript - 如何使用 ReactJs 从 JSON 文件中显示、添加和删除项目
- java - NullPointerException 尽管 fx:id 和 fx:controller 是正确的
- python - 我不知道为什么该代码的结果是 NONE
- sql - 通过 BigQuery 中的连接构建多级嵌套结构(使用嵌套和重复字段)
- reactjs - 如何使用 fetch 制作通用 API 调用函数
- sql-server - SQL Server FTS 索引正确的关键字但不返回这些关键字的结果
- android - showTimePicker 中的限制元素