如何计算数组中某些元素的数量? [英] How to count the number of certain element in an array?
本文介绍了如何计算数组中某些元素的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个数组 [1,2,3,5,2,8,9,2]
,我想查看多少 2
s数组中有。在没有使用 for
循环的情况下循环使用JavaScript的最优雅方法是什么?
If I have an array [1, 2, 3, 5, 2, 8, 9, 2]
, I would like to check how many 2
s there are in the array. What is the most elegant way to do it in JavaScript without looping with for
loop?
推荐答案
很简单:
var count = 0;
for(var i = 0; i < array.length; ++i){
if(array[i] == 2)
count++;
}
这篇关于如何计算数组中某些元素的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文