计数
 
 
方法一:普通的for循环
 
function count(arr
, item
) {
  let frequency 
= 0
  for(let i 
= 0; i 
< arr
.length
; i
++) {
    if(arr
[i
] === item
) {
      frequency
++
    }
  }
  return frequency
}
 
 
方法二:forEach
 
function count(arr
, item
) {
  let frequency 
= 0
  arr
.forEach(function(currentValue
) {
    if(currentValue 
=== item
) {
      frequency
++
    }
  })
  return frequency
}
 
 
方法三:filter
 
function count(arr
, item
) {
  let frequency 
= arr
.filter(function(currentValue
) {
    return currentValue 
=== item
  
})
  return frequency
.length
}
 
 
方法四:map(效率高于filter)
 
function count(arr
, item
) {
  let frequency 
= 0
  arr
.map(function(currentValue
) {
    if (currentValue 
=== item
) {
      frequency
++
    }
  })
  return frequency
}
 
 map函数和filter有点像,但是map是对数组中的所有元素进行复核函数条件的处理,最终得到的是一个新数组,元素个数不变。
 
filter函数虽然也是返回一个新数组,但是元素的个数等于复核函数条件的元素总和。
 
方法五:reduce
 
function count(arr
, item
) {
  let frequency 
= arr
.reduce(function(total
,currentValue
) {
    return currentValue 
=== item 
? total 
+ 1 : total
  
},0) 
  return frequency
}