2014-12-07 56 views
2

如何計算數組中元素的頻率,我是Javascript新手,完全丟失,我在這裏查看了其他答案,但無法獲取它們爲我工作。任何幫助深表感謝。用JavaScript計算數組中元素的頻率

function getText() { 
    var userText; 
    userText = document.InputForm.MyTextBox.value; //get text as string 
    alphaOnly(userText); 
} 

function alphaOnly(userText) { 
    var nuText = userText; 
    //result = nuText.split(""); 
    var alphaCheck = /[a-zA-Z]/g; //using RegExp create variable to have only  alphabetic characters 
    var alphaResult = nuText.match(alphaCheck); //get object with only alphabetic matches from original string 
    alphaResult.sort(); 
    var result = freqLet(alphaResult); 
    document.write(countlist); 
} 


function freqLet(alphaResult) { 
    count = 0; 
    countlist = { 
     alphaResult: count 
    }; 
    for (i = 0; i < alphaResult.length; i++) { 
     if (alphaResult[i] in alphaResult) 
      count[i] ++; 
    } 
    return countlist; 
} 

回答

2

要計算頻率,您應該使用對象的哪些屬性對應於輸入字符串中出現的字母。 同樣在增加屬性值之前,應該先檢查該屬性是否存在。

function freqLet (alphaResult){ 
    var count = {}; 
    countlist = {alphaResult:count}; 
    for (i = 0; i < alphaResult.length; i++){ 
    var character = alphaResult.charAt(i); 
    if (count[character]) { 
     count[character]++; 
    } else { 
     count[character] = 1; 
    } 
    } 
    return countlist; 
} 
+0

謝謝,但是我現在得到的錯誤,「TypeError:alphaResult.charAt不是一個函數」 – Confuddled 2014-12-07 22:35:11

+0

對不起,我忘了你的alphaResult不是一個字符串,而是一個數組。您應該將字符串從您的alphaOnly函數傳遞到我的freqLet函數。 – zavg 2014-12-08 00:30:48

0

如果你可以使用一個第三方庫,underscore.js提供確實幾乎正是你想要的功能「countBy」。

_.countBy(userText, function(character) { 
    return character; 
}); 

這應該被映射到的計數返回集合中的字符的關聯數組。

然後,您可以使用下劃線或任何您喜歡的方法再次將該對象的按鍵過濾到所需的受限字符集。