使用Javascript,那么你将如何迭代数组呢? 将结果存储到单个对象或变量中?我知道我可以轻松编写单独的函数来实现这一目标,但如果我需要在单个函数中执行此操作会怎样?
这段代码符合我的要求,但显然是重复的。你如何干掉这段代码并将结果返回一个变量?
var groupIds = ['G8372', 'G895', 'G12030'];
var groupOne = this.state.groups.find(g => g.get('extId') === groupIds[0]);
var groupTwo = this.state.groups.find(g => g.get('extId') === groupIds[1]);
var groupThree = this.state.groups.find(g => g.get('extId') === groupIds[2]);
var groupOneMembers = groupOne.get('members')
.filter(member => member.get('role') === 'member');
var groupTwoMembers = groupTwo.get('members')
.filter(member => member.get('role') === 'member');
var groupThreeMembers = groupThree.get('members')
.filter(member => member.get('role') === 'member');
var totalMembers = groupOneMembers.size + groupTwoMembers.size + groupThreeMembers.size;
return totalMembers;
答案 0 :(得分:1)
像这样:
let total = 0;
for (let gid of ['G8372', 'G895', 'G12030']) {
total +=
this.state.groups.find(g => g.get('extId') === gid)
.get('members').filter(member => member.get('role') === 'member')
.size;
}
return total;
答案 1 :(得分:0)
int
不是100%肯定你的数据组成。