返回句子中最大单词的长度

时间:2016-11-16 13:03:10

标签: javascript

我写了一个函数,它接收一个句子并计算该句子中最长的单词。

function findLongestWord(str) {

  var charArray = str.split(" ");
  var wordArray = [];


  for(var i = 0; i < charArray.length; i++ ) {
    wordArray.push(charArray[i].length);
    wordArray.sort();
    wordArray.reverse();

  }

  return wordArray[0];
}

我的功能适用于输入,例如:

findLongestWord("The quick brown fox jumped over the lazy dog");

但是当我通过它时:

findLongestWord("What if we try a super-long word such as otorhinolaryngology")

该函数返回:

4

而不是

19

11 个答案:

答案 0 :(得分:26)

您的排序功能以词汇方式对数组进行排序,因此您最终会使用

[1,10,19,2,2,2,3,4,4,4]

扭转这一点,你得到了

[4,4,4,3,2,2,2,19,10,1]

其中4是第一个数字

您根本不需要排序,只需使用Math.max

function findLongestWord(str) {
    return Math.max.apply( null, str.split(" ").map( (x) => x.length) );
}

答案 1 :(得分:25)

TL; DR

您的号码将按字符串排序。

要将它们按数字排序,按降序排列,在函数中应该执行以下操作:

wordArray.sort(function(a, b) { return b - a; });

说明

根据the docs

  

sort()方法对数组中的元素进行排序并返回   数组。排序不一定是stable默认排序   order是根据字符串Unicode代码点。

     

[...]

     

语法

     

arr.sort()

     

arr.sort(compareFunction)

     

参数

     

compareFunction可选

     

指定定义排序顺序的函数。 如果省略,则根据每个字符的Unicode代码点对数组进行排序   值,根据每个元素的字符串转换。

强调我的,所以你最终得到这样的东西:

var str = "What if we try a super-long word such as otorhinolaryngology";
var charArray = str.split(" ");
// now charArray == ["What", "if", "we", "try", "a", "super-long", "word", "such", "as", "otorhinolaryngology"]
// when you take the length of each word and end up with
var wordArray = [4, 2, 2, 3, 1, 10, 4, 4, 2, 19];
// and if you use plain wordArray.sort() without specific sort function you get
wordArray = [1, 10, 19, 2, 2, 2, 3, 4, 4, 4];
// and once reversed it is
wordArray = [4, 4, 4, 3, 2, 2, 2, 19, 10, 1];
// this is why you end up with wordArray[0] == 4

您还可以将整个功能实现为单行:

&#13;
&#13;
function findLongestWord(str) {
  return str.split(/\s+/).sort(function(a, b) { return b.length - a.length; })[0].length;
}

console.log("Longest word length = ", findLongestWord("The default sort order is according to string Unicode code points"));

console.log("Longest word length = ", findLongestWord("What if we try a super-long word such as otorhinolaryngology"));
&#13;
&#13;
&#13;

答案 2 :(得分:15)

与您的代码略有不同,但这应该有相同的结果!

function longestWord(string) {
    var str = string.split(" ");
    var longest = 0;
    for (var i = 0; i < str.length; i++) {
        if (longest < str[i].length) {
            longest = str[i].length;
        }
    }
    return longest;
}

console.log(longestWord("The quick brown fox jumped over the lazy dog"));
console.log(longestWord("What if we try a super-long word such as otorhinolaryngology"));

答案 3 :(得分:6)

您可以获得一系列单词,然后使用Math.max.apply

function findLongestWord(str){
  return Math.max.apply(null, str.split(" ").map(x=>x.length));
}

var l = findLongestWord("What if we try a super-long word such as otorhinolaryngology")

console.log(l)

答案 4 :(得分:4)

function findLongestWord(str) {
  return str.split(' ').reduce((m, w) => Math.max(m, w.length), 0);
}

var result = findLongestWord('The quick brown fox jumped over the lazy dog');
console.log(result);

答案 5 :(得分:4)

使用mapmax更好地解决问题(在我看来):

function findLongestWord(str) {
    return Math.max.apply(null, str.split(" ").map(function(word){
        return word.length;
    }));
}

答案 6 :(得分:3)

最短路:

console.log(
  'What if we try a super-long word such as otorhinolaryngology'
  .split(' ')
  .sort(function(a, b) {
    return b.length - a.length
  })[0].length
);

或作为一项功能:

function returnLongest(str) {
  return str
    .split(' ')
    .sort(function(a, b) {
      return b.length - a.length
    })[0].length;
}
console.log(returnLongest('What if we try a super-long word such as otorhinolaryngology'))

答案 7 :(得分:2)

您不必使用数组。如果您只想保存最长的单词,只需将最长的大小与当前的单词大小进行比较

function findLongestWord(str) {
  var charArray = str.split(" ");
  var longestWord = 0;

  for (var i = 0; i < charArray.length; i++) {
    let l = charArray[i].length;
    if (l > longestWord)
      longestWord = l;
  }
  return longestWord;
}

console.log(findLongestWord("The quick brown fox jumped over the lazy dog"));
console.log(findLongestWord("What if we try a super-long word such as otorhinolaryngology"));

答案 8 :(得分:1)

sort函数将以字典方式对数组进行排序,这不是您想要的。如果您想要对数字进行完美的升序排序,您还需要传递排序方法。此外,您正在for循环中对数组进行排序和反转,因此每次添加项时都会这样做。

你应该做的是:

for(var i = 0; i < charArray.length; i++ ) {
    wordArray.push(charArray[i].length);
  }

wordArray.sort(ascendingSort);
wordArray.reverse();

function ascendingSort(a, b) {
    return a - b;
}

return wordArray[0];

答案 9 :(得分:0)

你需要传递一个函数来排序:

function findLongestWord(str) {

  var charArray = str.split(" ");
  var wordArray = [];


  for(var i = 0; i < charArray.length; i++ ) {
    wordArray.push(charArray[i].length);
    wordArray.sort(function(a,b){
        return a > b;
    });
    wordArray.reverse();

  }

  return wordArray[0];
}

var longest = findLongestWord("What if we try a super-long word such as otorhinolaryngology");

答案 10 :(得分:0)

请尝试以下

,而不是推动长度并对其进行排序
 function findLongestWord(str) {

  var charArray = str.split(" ");
  var longestWordLength = 0;
  var longestWord = "";

  for(var i = 0; i < charArray.length; i++ ) {
    if(charArray[i].length > longestWordLength){
      longestWordLength = charArray[i].length;
      longestWord = charArray[i]
    }
  }
  return {longestWord , longestWordLength};
}