You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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 sentence as stntence in two places (var place = stntence.indexOf(...) and the initial if check). JavaScript can't find a variable named stntence, which breaks the assignment to place—hence the "place var is not defined" error.
  • Loop Logic Bug: counter = place++ uses post-increment, which means you're setting counter to the original place value before incrementing it. This will cause an infinite loop because you'll keep searching from the same starting position. You need to set counter to place + 1 instead to skip past the found match.
  • Redundant Condition: The if (place != -1) inside the while loop is unnecessary, since the while condition 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?

  1. Corrected the sentence spelling everywhere it was miswritten as stntence—this fixes the "place var is not defined" error.
  2. Updated counter = place + 1 to ensure we search from the character right after the found match, preventing infinite loops.
  3. Moved the "That's all" message outside the while loop so it only prints once after all matches are found.
  4. Used strict inequality (!==) instead of loose inequality (!=) for more precise checks (a good JavaScript practice).

内容的提问来源于stack exchange,提问作者lir5222

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:56:02