假设我有一个名为friends的对象数组
let friends = [
{"name": "test 1", "type": "pending"},
{"name": "test 2", "type": "friends"},
{"name": "test 3", "type": "friends"},
{"name": "test 4", "type": "friends"},
{"name": "test 5", "type": "alien"}
]
我如何获得将被排除在外的朋友的长度?我使用这个,但有更简单的方法吗?
let total = friends.filter(friend=>friend.type==='friends').length + friends.filter(friend=>friend.type==='alien').length;
答案 0 :(得分:2)
您不需要filter
该数组创建新数组然后获取其长度,只需使用函数reduce
进行简单计数。
let friends = [ {"name": "test 1", "type": "pending"}, {"name": "test 2", "type": "friends"}, {"name": "test 3", "type": "friends"}, {"name": "test 4", "type": "friends"}, {"name": "test 5", "type": "alien"}],
count = friends.reduce((a, t) => a + (t.type !== 'pending'), 0);
console.log(count);

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)
您可以直接使用 let friends = [
{"name": "test 1", "type": "pending"},
{"name": "test 2", "type": "friends"},
{"name": "test 3", "type": "friends"},
{"name": "test 4", "type": "friends"},
{"name": "test 5", "type": "alien"}
];
let count = friends.filter(t=>t.type !== 'pending').length;
console.log(count);
<强>样本强>
{{1}}