js统计字符串每个字符出现的次数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>统计次数</title>
</head>
<body>
<h1>const str = 'abc;uag;yafu;bda' 统计字符串每个字符出现的次数</h1>
</body>
<script>
const str = "abc;uag;yafu;bda";
const charCount = str.split("").reduce((pre, cur) => {
if (cur in pre) {
pre[cur]++;
} else {
pre[cur] = 1;
}
return pre;
}, {});
console.log(JSON.stringify(charCount));
let charCount2 = {};
const arr = str.split("");
for (let i = 0; i < arr.length; i++) {
const key = arr[i];
if (charCount2[key]) {
charCount2[key]++;
} else {
charCount2[key] = 1;
}
}
console.log(JSON.stringify(charCount2));
</script>
</html>