如何验证一组键值对中是否存在特定值?

时间:2016-04-09 10:04:22

标签: jquery

假设:

var dic = {1: 11, 2: 22, 3:22, 4:44, 5:22};

如何使用jQuery有效地找出22对该组中的键的值的次数?

1 个答案:

答案 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