Javascript:编写一个返回字符串中最长单词的函数。没有使用jquery

时间:2015-04-19 06:48:20

标签: javascript arrays function nested-loops

这是我第一次在这里发帖,我只是这样做,因为我已经到处研究过了​​。有些问题编码相似,但他们并没有找到合适的东西来帮助我。



var sentence = "The Shattuck is the best"

var longest = function(str) {
  var strArr = str.split(" ");
  for (var i = 0; i < strArr.length; i++) {
    for (var j = 0; j < strArr.length; j++) {
      if (strArr[i].length > strArr[j].length) {
        strArr.splice(j, 1);
      } else {
        j = 0
      }
    }
  }
  return strArr
};
longest(sentence);
//should return Shattuck but I get an infinite loop problem.
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:3)

数组方法reduce是一种我会采用的有趣方法。

var sentence = "The Shattuck is the best"
var words = sentence.split(" ")

words.reduce(function(a, b) {return a.length > b.length ? a : b})
// returns "Shattuck"

答案 1 :(得分:1)

您始终可以根据字长对数组进行排序,并向程序询问第一个值。

var Words = ["The", "Shattuck", "is", "the", "best"],
    sort = Words.sort(function (a, b) {
    return a.length < b.length;
});

console.log(sort);
console.log(sort[0]);

答案 2 :(得分:0)

对于不支持reduce的浏览器,请尝试

&#13;
&#13;
var sentence = "The Shattuck is the best"

var lon=-1,len=0, longest=function(str) {
  if (str.length>0) { // make sure we have a string
    var strArr = str.split(" "); // split on space
    for (var i = 0; i < strArr.length; i++) { // loop
      if (strArr[i].length>len) { // if the new length is longer
        lon = i; // save the index 
        len=strArr[i].length; // overwrite the saved length
      }
    }
    return strArr[lon]; // return the longest
  }
};
var word = longest(sentence);
alert(word)
&#13;
&#13;
&#13;