提示输入 5 个单词然后显示最长的单词 javascript

Prompt for 5 words then display longest word javascript

我正在尝试提示输入 5 个单词,然后将这些单词分开以找到最长的单词,然后使用 java 脚本显示最长的单词。我能够让任何东西工作,它甚至不会提示输入这些词。

function longestWord(string) {
    var word = prompt("Enter a string of at least 5 words separated by spaces:") ;
    var str = string.split(" ");
    var longest = 0;
    str.forEach(function(str) {
        if (longest < str.length) {
            longest = str.length;
            word = str;
        }
    });
    return word;
    document.write("The longest word is " +word+ ".") ;
}
longestWord(string)

这是你的函数的一个工作版本,结合了对原始问题的所有评论。

function longestWord() {
    var word = prompt("Enter a string of at least 5 words separated by spaces:") ;
    var str = word.split(" ");
    var longest = 0;
    str.forEach(function(str) {
        if (longest < str.length) {
            longest = str.length;
            word = str;
        }
    });
    return word;
}

document.write("The longest word is " + longestWord() + ".");

您正在使用未定义的字符串作为参数调用 longestWord。

<script>
function longestWord() {
    string = prompt("Enter a string of at least 5 words separated by spaces:") ;
    var str = string.split(" ");
    var longest = 0;
    str.forEach(function(str) {
        if (longest < str.length) {
            longest = str.length;
            word = str;
        }
    });
    document.write("The longest word is " +word+ ".") ;
}
longestWord();
</script>

我会采取不同的做法:分开

function longestWord(string) {
  var str = string.split(" ");
  var word = str[0];
  for (s of string.split(" ")) {
    if (s.length > word.length) {
      word = s;
    }
  }

  return word;
}
var words = prompt("Enter a string of at least 5 words separated by spaces:");
lw = longestWord(words);
document.getElementById("longest_word").innerHTML = "The longest word is " + lw + ".";
<div id='longest_word'>
  longest word:
</div>

来自 activity 的函数: