JavaScript 错误:未捕获的类型错误:undefined 不是第 4 行的函数;我不知道我做错了什么



我试图让用户写一个句子,然后让计算机在单独的"确认窗口"中确认每个单词,而不使用空格。为了确定此代码是否是执行此任务的正确代码,我必须运行代码,但是我收到第四行标题中列出的错误。首先,我不明白错误在说什么。如果它告诉我在第四行,if语句不是一个函数,它不能运行它,那么怎么会呢?

<script>
function sentenceFinder (sentence){
    for (counter = 0; counter < sentence.length; counter++){
        if (sentence.substring(counter, counter + 1) !== " "){
            words.push(sentence.substring(counter, counter + 1));
        }
        else {
            comfirm(words[0]);
        }
     };
}
var x = prompt("Please type in the sentence that will be seperated.")
sentenceFinder(x)
var words = []
</script>

您有两个导致错误的问题。

  1. 正在使用我认为您打算使用substring subscript.
  2. 在将words设置为数组之前,您正在使用它。

我想这就是你打算写的。

function sentenceFinder (sentence){
    for (counter = 0; counter < sentence.length; counter++){
        if (sentence.substring(counter, counter + 1) !== " "){
            words.push(sentence.substring(counter, counter + 1));
        }
        else {
            comfirm(words[0]);
        }
     };
}
var words = [];
var x = prompt("Please type in the sentence that will be seperated.");
sentenceFinder(x);

最新更新