Javascript返回相同数组出现的计数

时间:2017-09-08 03:55:25

标签: javascript arrays

我有这个数组

array = [{name:name1,score:4},{name:name2,score:4},{name:name3,score:4}]

并且,我希望得到这个数组的出现次数,得分为4,

result = 3

Thankstack

2 个答案:

答案 0 :(得分:0)

您可以迭代您的数组。这是代码,

 var array = [{
   name: "name1",
   score: 4
 }, {
   name: "name2",
   score: 4
 }, {
   name: "name3",
   score: 4
 }];

 function getCount(array) {
   var i, object, count = 0;
   for (i = 0; i < array.length; i = i + 1) {
     object = array[i];
     if (object.score === 4) {
       count = count + 1;
     }
   }
   return count;
 }
 alert(getCount(array));

答案 1 :(得分:0)

你可以试试这个:

var array = [{name:name1,score:4},{name:name2,score:4},{name:name3,score:4}];
var count=0;
array.forEach(function(data){
   if(data.score==4){
   count++;
   }
});
console.log("Total count: "+count);