需要有關為什么我在 javascript 中的遞回程式不起作用的幫助。它應該從文本檔案中獲取單詞并顯示其中的單詞數、行數和字符數。請幫我修改我的代碼或告訴我我的錯誤在哪里,因為我不知道在哪里。這是javascript代碼:
var fs = require("fs");
var text = fs.readFileSync("text.txt", "utf8");
function countLines(text) {
if (text == "") {
return 0;
} else {
return 1 countLines(text.substring(text.indexOf("\n") 1));
}
}
function countWords(text) {
if (text == "") {
return 0;
} else {
return 1 countWords(text.substring(text.indexOf(" ") 1));
}
}
function countCharacters(text) {
if (text == "") {
return 0;
} else {
return 1 countCharacters(text.substring(1));
}
}
var lineCount = countLines(text);
var wordCount = countWords(text);
var characterCount = countCharacters(text);
console.log(
"There are "
lineCount
" lines, "
wordCount
" words, and "
characterCount
" characters in the file."
);
這是 text.txt 檔案:
I was running to the zoo.
uj5u.com熱心網友回復:
您的問題是盲目遞回而不檢查indexOf的結果,當找不到目標時為-1
所以
text.substring(text.indexOf(" ") 1)
變成
text.substring(-1 1)
換句話說
text.substring(0)
所以,你無限遞回最后一個詞(和行,就此而言)
如果.indexOf回傳 -1,你應該return 1
注意:我在您的代碼中洗掉了不必要的 -當回傳值時else不需要- 這使得代碼更清晰(在我看來,如果必須,歡迎您使用 elseelseif
我展示了兩種不同的測驗方法indexOf
var text = "I was running to the zoo.";
function countLines(text) {
if (text == "") {
return 0;
}
const index = text.indexOf("\n");
if (index < 0) {
return 1;
}
return 1 countLines(text.substring(index 1));
}
function countWords(text) {
if (text == "") {
return 0;
}
const index = text.indexOf(" ") 1;
if (index) { // since we've added 1, a "not found" -1 would be 0 here, and be falsey
return 1 countWords(text.substring(index));
}
return 1;
}
function countCharacters(text) {
if (text == "") {
return 0;
}
return 1 countCharacters(text.substring(1));
}
var lineCount = countLines(text);
var wordCount = countWords(text);
var characterCount = countCharacters(text);
console.log(
"There are "
lineCount
" lines, "
wordCount
" words, and "
characterCount
" characters in the file."
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/515660.html
標籤:javascript递归
