关于javascript:返回句子中最大单词的长度

Returning the length of largest word in a sentence

本问题已经有最佳答案,请猛点这里访问。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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];
}

我的函数与输入一起工作,例如:

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

但当我通过时:

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

函数返回:

1
4

而不是

1
19


排序函数按词汇对数组进行排序,因此最终

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

反过来,你会

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

其中,4是第一个数字

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

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


DR

您的数字将按字符串排序。

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

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

解释

根据文件:

The sort() method sorts the elements of an array in place and returns
the array. The sort is not necessarily stable. The default sort
order is according to string Unicode code points.

[...]

Syntax

arr.sort()

arr.sort(compareFunction)

Parameters

compareFunction Optional

Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point
value, according to the string conversion of each element.

强调我的,所以你最终会得到这样的结果:

1
2
3
4
5
6
7
8
9
10
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

您还可以将整个函数实现为一行程序:

1
2
3
4
5
6
7
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"));


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

1
2
3
4
5
6
7
8
9
10
11
12
13
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"));


你可以得到一个字长数组,然后使用Math.max.apply

1
2
3
4
5
6
7
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)


在我看来,使用mapmax更好地解决这个问题:

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


1
2
3
4
5
6
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);


最短路线:

1
2
3
4
5
6
7
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
);

或者作为函数:

1
2
3
4
5
6
7
8
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'))


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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"));


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

你应该做的是:

1
2
3
4
5
6
7
8
9
10
11
12
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];


请尝试以下操作,而不是按长度排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 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};
}


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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");