计算相同值出现在 javascript 数组中的次数
问题描述:
我想知道是否有与此相同的本机 javascript 代码:
I would like to know if there is a native javascript code that does the same thing as this:
function f(array,value){
var n = 0;
for(i = 0; i < array.length; i++){
if(array[i] == value){n++}
}
return n;
}
答
为此目的可能有不同的方法.
并且您使用 for
循环的方法显然没有错位(除了它代码量看起来很冗余.
这里有一些额外的方法来获取数组中某个值的出现:
There might be different approaches for such purpose.
And your approach with for
loop is obviously not misplaced(except that it looks redundantly by amount of code).
Here is some additional approaches to get the occurrence of a certain value in array:
使用
Array.forEach
方法:
var arr = [2, 3, 1, 3, 4, 5, 3, 1];
function getOccurrence(array, value) {
var count = 0;
array.forEach((v) => (v === value && count++));
return count;
}
console.log(getOccurrence(arr, 1)); // 2
console.log(getOccurrence(arr, 3)); // 3
使用Array.filter
方法:
function getOccurrence(array, value) {
return array.filter((v) => (v === value)).length;
}
console.log(getOccurrence(arr, 1)); // 2
console.log(getOccurrence(arr, 3)); // 3