如何計算數組中元素的頻率,我是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;
}
謝謝,但是我現在得到的錯誤,「TypeError:alphaResult.charAt不是一個函數」 – Confuddled 2014-12-07 22:35:11
對不起,我忘了你的alphaResult不是一個字符串,而是一個數組。您應該將字符串從您的alphaOnly函數傳遞到我的freqLet函數。 – zavg 2014-12-08 00:30:48