3 回答

TA貢獻1780條經(jīng)驗 獲得超1個贊
只需遍歷字符串的每個字符,并將它們計數(shù)到一個對象中。
一個簡單的解決方案是:
let str = "The quick brown fox jumps over the lazy dog";
const count = string => {
const characters = {};
for (let character of string) {
characters[character] = characters[character] + 1 || 1;
}
return characters;
}
console.log(count(str));
您可以將結果用作:
let result = count(str);
console.log(result["o"]); // 4
更新
如果您需要字符串輸出,一種選擇是使用第二個循環(huán)來寫出結果:
let str = "The quick brown fox jumps over the lazy dog";
const count = string => {
const characters = {};
let str = "";
for (let character of string) {
characters[character] = characters[character] + 1 || 1;
}
for (let key in characters) {
str += `${key}${characters[key]}`
}
return str;
}
console.log(count(str));
或者,如果您只是簡單地不關心格式:
return JSON.stringify(characters);

TA貢獻1848條經(jīng)驗 獲得超2個贊
我認為最簡單和最易讀的
const countChars = str => {
const chars = {}; // create a counter object
const arr = str.split(""); // make an array from the characters
arr.forEach(char => chars[char] = ++chars[char] || 1) // add counters to counter object
return arr // return the array but first
.map(char => char + chars[char]) // map to counters
.join(""); // and then join to string
}
console.log(countChars("Now is the time"));
按第一次出現(xiàn)的順序減少到只是 char + number
const countChars = str => {
const chars = {}; // create a counter object
const arr = str.split(""); // make an array from the characters
arr.forEach(char => chars[char] = ++chars[char] || 1) // add counters to counter object
return Object.keys(chars) // return the chars
.map(char => char + chars[char]) // concatenated with counters
.join(""); // and then join to string
}
console.log(countChars("woof the looping loop"));

TA貢獻1898條經(jīng)驗 獲得超8個贊
Object.entries()您可以使用,reduce()和flat()方法嘗試此操作:
function strLetterCount(str) {
return Object.entries([...str].reduce(function(ac, s) {
ac[s] = ++ac[s] || 1
return ac;
}, {})).flat().join('')
}
console.log(strLetterCount("taco"))
console.log(strLetterCount("chocotaco"))
解釋:
使用
[...str]
我們首先將字符串轉換為數(shù)組。然后使用
.reduce()
我們試圖將每個字符串元素的計數(shù)和存儲到一個對象中,例如:{t: 1, a: 1, c: 1, o: 1}
然后使用
Object.entries()
我們得到如下數(shù)據(jù):[["t", 1], ["a", 1], ["c", 1], ["o", 1]]
最后使用
flat()
&join()
我們得到所需的輸出格式為字符串t1a1c1o1
添加回答
舉報