JavaScript 计数出现次数通常是指在一个数组或字符串中统计某个元素或字符出现的次数。这在数据处理和分析中非常常见。
function countOccurrences(arr, target) {
return arr.reduce((count, item) => {
return item === target ? count + 1 : count;
}, 0);
}
const array = [1, 2, 3, 4, 2, 2, 3];
const target = 2;
console.log(countOccurrences(array, target)); // 输出: 3
function countOccurrences(str, target) {
let count = 0;
let index = str.indexOf(target);
while (index !== -1) {
count++;
index = str.indexOf(target, index + 1);
}
return count;
}
const string = "hello world, hello universe";
const target = "hello";
console.log(countOccurrences(string, target)); // 输出: 2
原因:
解决方法:
function countOccurrences(arr, target) {
if (!Array.isArray(arr) || arr.length === 0) return 0;
return arr.reduce((count, item) => {
return item === target ? count + 1 : count;
}, 0);
}
原因:
解决方法:
function countOccurrences(arr, target) {
const map = {};
arr.forEach(item => {
if (item === target) {
map[item] = (map[item] || 0) + 1;
}
});
return map[target] || 0;
}
希望这些信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云