當前位置:網站首頁>面試之求一串字符串中每個字符的出現次數

面試之求一串字符串中每個字符的出現次數

2022-01-27 22:09:46 .ToString()°

求一串字符串中每個字符的出現次數

  • for循環實現,最容易理解:
var arrString = 'fghffgaga';
var strArr = arrString.split('');
var rel = {
    };
var count = 1;
for (var i = 0; i < strArr.length; i++) {
    
    for (var j = i + 1; j < strArr.length; j++) {
    
        if (strArr[i] == strArr[j]) {
    
            count++;
            strArr.splice(j, 1);
            j = j - 1;              
        }

    }
    var qcount = count;
    count = 1;
    rel[strArr[i]] = qcount;    
}
console.log(rel); // {f: 3, g: 3, h: 1, a: 2}
  • reduce() 方法實現
var arrString = 'fghffgaga';
var rel = arrString.split('').reduce(function(res, cur) {
    
res[cur] ? res[cur] ++ : res[cur] = 1
return res;
}, {
    })
console.log(rel); // {f: 3, g: 3, h: 1, a: 2}

版權聲明
本文為[.ToString()°]所創,轉載請帶上原文鏈接,感謝
https://cht.chowdera.com/2022/01/202201272209458219.html

隨機推薦