该算法计算数组中元素的出现次数
var numbers = [2, 4, 4, 7, 6, 8, 4];
function howMany(array, value) {
var n = 0;
for (var i = 0; i < array.length; i++)
if (array[i] == value)
n++;
return n;
}
console.log(howMany(numbers, 3)); // -> 0
console.log(howMany(numbers, 4)); // -> 3
console.log(howMany(numbers, 5)); // -> 0
console.log(howMany(numbers, 6)); // -> 0
数组应该有对应的方法吗?
您可以使用闭包来保存第一次遍历数组的结果并重用它们。
评论中free_ze的回答解决了这个问题