我有一系列待办事项,我试图显示已完成的未完成待办事项的数量。我知道我可以执行 array.length 并且可以找到总数量,但在这种情况下我是堆栈。
this.state = {
text: '',
notes: [
{todo: "hello", completed: true},
{todo: "world", completed: false}
]
}
全部(notes.length) 2 已完成(?) 0 未完成(?) 0
最佳答案
使用过滤器
let completedCount = this.state.notes.filter(n => n.completed).length;
let incompleteCount = this.state.notes.length - completedCount;
或使用减少
let result = this.state.notes.reduce( (acc, curr) => {
if(curr.completed) acc.complete++;
else acc.incomplete++;
return acc;
}, {complete:0,incomplete:0});
console.log(result.complete); // 1
console.log(result.incomplete); // 1
关于javascript - 如何根据 obj 标志的状态查找数组长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51628337/