Liczenie słów w łańcuchu
function WordCount(str) {
var totalSoFar = 0;
for (var i = 0; i < WordCount.length; i++)
if (str(i) === " ") { // if a space is found in str
totalSoFar = +1; // add 1 to total so far
}
totalsoFar += 1; // add 1 to totalsoFar to account for extra space since 1 space = 2 words
}
console.log(WordCount("Random String"));
Myślę, że całkiem dobrze to zrozumiałem, chyba że myślę, żeif
oświadczenie jest błędne. Jak powiedziećif(str(i)
zawiera spację, dodaj 1.
Edytować:
Dowiedziałem się (dzięki Blenderowi), że mogę to zrobić o wiele mniej kodu:
function WordCount(str) {
return str.split(" ").length;
}
console.log(WordCount("hello world"));