简体   繁体   English

如何使用javascript查找字符串中最大单词的长度?

[英]How to find the length of the largest word in a string with javascript?

 function findLongestWordLength(str) { var res = str.split(" "); var ar = []; for (let i = 0; i < res.length; i++) { let leength = res[i].length; ar.push(leength); //ar is the array of the lengths of the word in the string. } var largest = 0; for (let i = 0; i <= largest; i++) { if (ar[i] > largest) { var largest = ar[i]; } //this loop is detecting largest number from the array ar. } return largest; } console.log(findLongestWordLength("What if we try a super-long word such as otorhinolaryngology"));

I want the largest word length from a string,我想要字符串中最大的字长,

This is working for maximum string but is not working for this coressponding array "What if we try a super-long word such as otorhinolaryngology"这适用于最大字符串,但不适用于此核心响应数组“如果我们尝试使用超长单词,例如耳鼻喉科会怎样”

You have你有

var largest = 0;
for (let i = 0; i <= largest; i++) {

You're iterating over the ar from indicies 0 to whichever index first sets largest to something larger than the current index.您将ar从索引 0 迭代到第一个将largest设置为大于当前索引的索引。 Use i < ar.length instead:使用i < ar.length代替:

 function findLongestWordLength(str) { var res = str.split(" "); var ar = []; for (let i = 0; i < res.length; i++) { let leength = res[i].length; ar.push(leength); //ar is the array of the lengths of the word in the string. } var largest = 0; for (let i = 0; i < ar.length; i++) { if (ar[i] > largest) { var largest = ar[i]; } //this loop is detecting largest number from the array ar. } return largest; } console.log(findLongestWordLength("What if we try a super-long word such as otorhinolaryngology"))

But spreading the mapped word lengths into Math.max might be easier:但是将映射的字长扩展到Math.max可能更容易:

 const findLongestWordLength = str => Math.max( ...str.split(' ').map(word => word.length) ); console.log(findLongestWordLength("What if we try a super-long word such as otorhinolaryngology"))

Try splitting the input on whitespace, then sorting the array by length:尝试在空白处拆分输入,然后按长度对数组进行排序:

 var input = "What if we try a super-long word such as otorhinolaryngology"; var parts = input.split(/\\s+/); parts.sort(function(a, b) { return b.length - a.length; }); console.log(parts[0]);

 //Let us take an example let givenSen = "Shiva is a good guy"; //Here we are splitting with space //So we will get ["Shiva", "is", "a", "good", "guy"] //and sorting based on length //remeber ab (ascending order), ba (decending order) //0(zero) represents first element let largestWord = givenSen.split(" ").sort(function(a,b){return(b.length - a.length)})[0] //cosole console.log(largestWord.length)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM