如何編寫一個計算字符串中每個字符出現次數的JavaScript代碼?每個字符出現在一個字符串中
e.g
String is : Hello World
Output :
count of H -> 1
count of e -> 1
count of l -> 3
count of o -> 2
count of r -> 1
count of d -> 1
count of W -> 1
如何編寫一個計算字符串中每個字符出現次數的JavaScript代碼?每個字符出現在一個字符串中
e.g
String is : Hello World
Output :
count of H -> 1
count of e -> 1
count of l -> 3
count of o -> 2
count of r -> 1
count of d -> 1
count of W -> 1
此代碼應工作:
var str = "Hello World";
var arr = str.split('');
var occ = {};
for(var i=0,c=arr.length;i<c;i++){
if(occ[arr[i]]) occ[arr[i]]++;
else occ[arr[i]] = 1;
}
for(var i in occ){
alert('count of '+i+' -> '+occ[i]);
}
var counts = {};
yourstring.split('').map(function(ch) {
counts[ch] = (counts[ch] || 0) + 1;
});
或者是髖關節和使用的map/reduce:
var counts = yourstring.split('').reduce(function(dst, c) {
dst[c] = (dst[c] || 0) + 1;
return dst;
}, {});
+1爲迄今最優雅的答案 – Saju 2013-02-10 13:18:06
唯一要注意的是這個Array_map'和'Array.reduce'只在IE9 +中本機支持。其他瀏覽器應該適用於大多數版本。請參閱[瀏覽器兼容性圖表](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map#Browser_compatibility) – 2013-02-10 13:22:17
var splitWord = "Hello World".split('');
var letters = {};
for(var i in splitWord)
{
var letter = splitWord[i];
if(letter == ' ') continue;
if(typeof letters[letter] == 'undefined')
{
letters[letter] = 0;
}
letters[letter]++;
}
console.dir(letters);
我試圖分裂,比賽,但它沒有工作... – Vikash 2013-02-10 13:11:08