我想知道是否存在与此相同的原生javascript代码:
function f(array,value){
var n = 0;
for(i = 0; i < array.length; i++){
if(array[i] == value){n++}
}
return n;
}
答案 0 :(得分:11)
为此目的可能有不同的方法。
你的for
循环方法显然没有错位(除了它看起来多余的代码量)。
这是一些额外的在数组中获得某个值的方法:
使用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
答案 1 :(得分:5)
您可以使用reduce来实现目标:
var a = [1,2,3,1,2,3,4];
var map = a.reduce(function(obj, b) {
obj[b] = ++obj[b] || 1;
return obj;
}, {});
答案 2 :(得分:4)
另一个选择是:
count = myArray.filter(x => x == searchValue).length;
答案 3 :(得分:4)
这是我的解决方案,不使用其他对象,而使用reduce
:
const occurrencesOf = (number,numbers) => numbers.reduce((counter, currentNumber)=> (number === currentNumber ? counter+1 : counter),0);
occurrencesOf(1, [1,2,3,4,5,1,1]) // returns 3
occurrencesOf(6, [1,2,3,4,5,1,1]) // returns 0
occurrencesOf(5, [1,2,3,4,5,1,1]) // returns 1
答案 4 :(得分:1)
您也可以使用forEach
let countObj = {};
let arr = [1,2,3,1,2,3,4];
let countFunc = keys => {
countObj[keys] = ++countObj[keys] || 1;
}
arr.forEach(countFunc);
// {1: 2, 2: 2, 3: 2, 4: 1}
答案 5 :(得分:0)
您可能希望使用indexOf()
功能查找并计算value
array
function g(array,value){
var n = -1;
var i = -1;
do {
n++;
i = array.indexOf(value, i+1);
} while (i >= 0 );
return n;
}
答案 6 :(得分:0)
const arr = ["a", "a", "a", "b", "b", "b", "b", "c", "c", "c"];
count = 0;
function countValues(array, countItem) {
array.forEach(itm => {
if (itm == countItem) count++;
});
console.log(`${countItem} ${count}`);
}
countValues(arr, "c");
答案 7 :(得分:0)
let ar = [2,2,3,1,4,9,5,2,1,3,4,4,8,5];
const countSameNumber = (ar: any, findNumber: any) => {
let count = 0;
ar.map((value: any) => {
if(value === findNumber) {
count = count + 1;
}
})
return count;
}
let set = new Set(ar);
for (let entry of set) {
console.log(entry+":", countSameNumber(ar, entry));
}