2017-07-20 62 views
2

我遇到了一個關於使用HTML中的表單計算句子的問題,但我想先解決這個函數,看看它是否可行。這裏是我的功能,我一直無法得到它在的jsfiddle工作(https://jsfiddle.net/jdloomis/fxt81ynu/2/):使用Javascript中的函數計算句子

var numSentences = 0; 

function calSentences(longString) { 
    var length = longString.length; 
    var sentence = ''; 

for (var i = 0; i < length; i++) { 
    sentence += longString[i]; 

    if (longString[i] == '.') { 
    numSentences++; 
    sentence = ''; 
    } 
    } 
} 

console.log(calSentences("This is a sentence. My second sentence.")); 

我已經能搞清楚大部分功能和他們所做的事情在我的書中,除了這一年字數不使用.split,如果我無法弄清楚,我會在另一篇文章中發帖。

+0

問題是什麼? –

+0

我忘了返回變量。 –

回答

0

你是所以接近你的企圖!所有你忘了做是回報句子與return numSentences數量:

var numSentences = 0; 
 

 
function calSentences(longString) { 
 
    var length = longString.length; 
 
    var sentence = ''; 
 

 
    for (var i = 0; i < length; i++) { 
 
    sentence += longString[i]; 
 
    if (longString[i] == '.') { 
 
     numSentences++; 
 
     sentence = ''; 
 
    } 
 
    } 
 

 
    return numSentences; 
 
} 
 

 
console.log(calSentences("This is a sentence. My second sentence."));

希望這有助於! :)

+0

感謝您的幫助! –

0

你的代碼是正確的,但你沒有從你的函數返回任何東西。

此外,保留var numSentences局部於您的功能,以便它在每次運行您的功能時重置爲0。否則,每次運行該函數時都會添加上一次計算。

function calSentences(longString) { 
 
    var numSentences = 0; 
 
    var length = longString.length; 
 
    var sentence = ''; 
 

 
for (var i = 0; i < length; i++) { 
 
    sentence += longString[i]; 
 

 
    if (longString[i] == '.') { 
 
    numSentences++; 
 
    sentence = ''; 
 
    } 
 
    } 
 
    return numSentences; 
 
} 
 

 
console.log(calSentences("This is a sentence. My second sentence."));

+0

感謝您的幫助和提示! –