This question already has answers here:
How to count the number of occurrences of each item in an array? [duplicate]
(9个答案)
7年前关闭。
我想计算数组中每个元素的数量
例子:
然后我想输出
提前致谢
结果:
(9个答案)
7年前关闭。
我想计算数组中每个元素的数量
例子:
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 - jQuery计数数组中出现的次数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22557502/
10-12 15:59