我終於開始學習JavaScript了,出於某種原因,我無法獲得這個簡單的功能。請告訴我我做錯了什麼。簡單的JavaScript字數統計功能
function countWords(str) {
/*Complete the function body below to count
the number of words in str. Assume str has at
least one word, e.g. it is not empty. Do so by
counting the number of spaces and adding 1
to the result*/
var count = 0;
for (int 0 = 1; i <= str.length; i++) {
if (str.charAt(i) == " ") {
count ++;
}
}
return count + 1;
}
console.log(countWords("I am a short sentence"));
我得到一個錯誤SyntaxError: missing ; after for-loop initializer
感謝您的幫助
for循環結構應該是:for(var i = 0; i <= str.length; i ++) – Nile
@Nile:其實'i
Guffa
通過字符串中的每個字符做一個循環將是非常低效的我推薦你做下面的str.split('').length – elmuchacho