jQuery计数数组中的出现次数 [英] Jquery Count number of occurances in array
本文介绍了jQuery计数数组中的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想计算数组中每个元素的数量
I'd like to count the number of each element in my array
示例:
var basketItems = ['1','3','1','4','4'];
jQuery.each(basketItems, function(key,value) {
// Go through each element and tell me how many times it occurs, output this and remove duplicates
}
然后我想输出
Item | Occurances
--------------------
1 | 2
3 | 1
4 | 2
预先感谢
推荐答案
您可以尝试:
var basketItems = ['1','3','1','4','4'],
counts = {};
jQuery.each(basketItems, function(key,value) {
if (!counts.hasOwnProperty(value)) {
counts[value] = 1;
} else {
counts[value]++;
}
});
结果:
Object {1: 2, 3: 1, 4: 2}
这篇关于jQuery计数数组中的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文