谁能帮我解决这个问题。它似乎无法正常工作。应该在输入的所有单词串中找到最长的单词。当我运行它时,它返回字符串的第一个字符。

function LongestWord(sen) {

  var lrg = '';

  sen.split(" ");//seperates sen into words

  for(var i = 0;i<sen.length;i++){
    var check1 = sen[i];//assigns check1 as word in sen
    if(check1.length>lrg.length){//assigns length of longest word
      lrg = check1;

       }

  }
      return lrg;

}

// keep this function call here
// to see how to enter arguments in JavaScript scroll down
LongestWord(readline());

最佳答案

split方法返回一个新数组。尝试这个:

var arr = sen.split(" ");
for(var i = 0; i < arr.length; i++) {
    var check1 = arr[i];
    if(check1.length>lrg.length) {
        lrg = check1;
    }
}

return lrg;

07-24 16:19