使用indexOf的JS简易算法失效:提示place未定义如何解决?
Fixing the "place var is not defined" Error & Your Word Position Finder
Hey there! Let's get your word/tab position finder working right and squash that error. Here's a breakdown of the issues and the fixed code:
Key Issues in Your Original Code
- Critical Typo: You misspelled
sentenceasstntencein two places (var place = stntence.indexOf(...)and the initialifcheck). JavaScript can't find a variable namedstntence, which breaks the assignment toplace—hence the "place var is not defined" error. - Loop Logic Bug:
counter = place++uses post-increment, which means you're settingcounterto the originalplacevalue before incrementing it. This will cause an infinite loop because you'll keep searching from the same starting position. You need to setcountertoplace + 1instead to skip past the found match. - Redundant Condition: The
if (place != -1)inside thewhileloop is unnecessary, since thewhilecondition already checks for this.
Fixed Code
var sentence = prompt("Enter your sentence"); var word = prompt("Enter the tab/word you're looking for"); var counter = 0; // Fixed the typo here var place = sentence.indexOf(word, counter); if (place !== -1) { while (place !== -1) { console.log("The position of the word/tab is: " + place); // Update counter to start searching after the current match counter = place + 1; place = sentence.indexOf(word, counter); } console.log("That's all"); } else { console.log("The word/tab does not exist in the sentence"); }
What Changed?
- Corrected the
sentencespelling everywhere it was miswritten asstntence—this fixes the "place var is not defined" error. - Updated
counter = place + 1to ensure we search from the character right after the found match, preventing infinite loops. - Moved the "That's all" message outside the
whileloop so it only prints once after all matches are found. - Used strict inequality (
!==) instead of loose inequality (!=) for more precise checks (a good JavaScript practice).
内容的提问来源于stack exchange,提问作者lir5222
相关产品推荐
相关产品推荐

