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

时间:2015-05-22 15:49:30

标签: javascript string function split prompt

我试着提示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)

3 个答案:

答案 0 :(得分:2)

这是您的函数的工作版本,结合了原始问题的所有注释。

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() + ".");

答案 1 :(得分:0)

您正在使用字符串作为参数调用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>

答案 2 :(得分:0)

我会采用不同的方式:分开

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>

来自活动的功能: