假设:
var dic = {1: 11, 2: 22, 3:22, 4:44, 5:22};
如何使用jQuery有效地找出22
对该组中的键的值的次数?
答案 0 :(得分:1)
var dic = {1: 11, 2: 22, 3:22, 4:44, 5:22};
var vals = Object.values(dic); //Gives [11, 22, 22, 44, 22]
然后,遍历数组 vals
var count = 0;
jQuery.each(vals, function(i,v) { if (v === 22) count++; });
最后计数将包含所需元素的总出现次数
修改强>
即使上面的最后一行代码也可以放入函数中:
function countElement(ele) {
var count = 0;
jQuery.each(vals, function(i,v) { if (v === ele) count++; });
return count;
}
并称之为:
countElement(22); //Gives 3