句子代码中最长的单词不起作用

时间:2014-01-15 01:48:37

标签: javascript string for-loop split

任何人都可以帮我解决这个问题。它似乎没有正常工作。它应该找到输入其中的任何字符串中最长的单词。当我运行它时,它返回字符串的第一个字符。

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()); 

3 个答案:

答案 0 :(得分:4)

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; 

答案 1 :(得分:0)

您还可以使用正则表达式来检查字符串是否匹配。

var sentence = "seperates sen into words";
var splittedParts = sentence.match(/\w{1,}/gi);//You can also make use of regular //expression
for(var i = 0; i < splittedParts.length; i++) {
    var check1 = splittedParts[i];
    if(check1.length>=splittedParts.length) {
        splittedParts = check1;
    }
}
  alert(splittedParts);

答案 2 :(得分:0)

如果您匹配单词并按长度排序,则最长,

数组中的第一个单词将是最长的。

function longestWord(str){
    return str.match(/[a-zA-Z]+/g).sort(function(a, b){
        if(a.length=== b.length) return a<b? 1: a>b? -1: 0;
        return b.length-a.length;
    })[0];
}
var s1= 'It\'s more like it is today, than it ever was before.';


longestWord(s1)

/ *返回值:(String):在* /

之前

您可以使用filter -

返回相同长度的数组
function longestWords(str){
    return str.match(/[a-zA-Z]+/g).sort(function(a, b){
        if(a.length=== b.length) return a<b? 1: a>b? -1: 0;
        return b.length-a.length;
    }).filter(function(w, i, A){
        return w.length=== A[0].length;
    });
}

var s1= 'It  became more like it is today, than it ever did before.';
longestWords(s1)

/ *返回值:(数组):之前,变为* /