如何在JavaScript中统计字符串中每个连续唯一字符的出现次数
Solution for
CountUniqueChar() in JavaScript Hey there! Let's build this function that tracks consecutive character runs in a string and returns an array of count objects. The key thing here is we're counting consecutive occurrences, not total occurrences of each character across the entire string—your example makes that clear with the final "a" being a separate entry.
Step-by-Step Implementation
Here's how we can do this:
function CountUniqueChar(str) { // Handle empty string edge case first if (!str) return []; const result = []; let currentChar = str[0]; let currentCount = 1; // Loop through the string starting from the second character for (let i = 1; i < str.length; i++) { if (str[i] === currentChar) { // Same character as current, increment count currentCount++; } else { // Different character: push the current run to result, then reset result.push({ [currentChar]: currentCount }); currentChar = str[i]; currentCount = 1; } } // Don't forget to add the last character run! result.push({ [currentChar]: currentCount }); return result; }
How It Works
Let's walk through your example input "aaaasssiia" to see it in action:
- Start with
currentChar = "a",currentCount = 1 - Next three characters are "a" → count becomes 4
- Hit "s" → push
{"a": 4}to result, reset tocurrentChar = "s", count =1 - Next two "s" → count becomes 3
- Hit "i" → push
{"s":3}, reset to "i", count=1 - Next "i" → count becomes 2
- Hit final "a" → push
{"i":2}, reset to "a", count=1 - Loop ends, push
{"a":1}to result - Final output is exactly what you need:
[{"a": 4}, {"s": 3}, {"i": 2}, {"a": 1}]
Testing the Function
You can test it with your example like this:
console.log(CountUniqueChar("aaaasssiia")); // Output: [ { a: 4 }, { s: 3 }, { i: 2 }, { a: 1 } ]
It also handles edge cases like empty strings (CountUniqueChar("") returns []) or single-character strings (CountUniqueChar("z") returns [{"z":1}]).
内容的提问来源于stack exchange,提问作者bankzAladin
相关产品推荐
相关产品推荐

