简体   繁体   English

JavaScript:查找字符串中最大的单词

[英]JavaScript: Finding the largest word in a string

This is my snippet. 这是我的片段。 I feel this code satisfies the algorithm, but it does not pass. 我觉得这段代码满足了算法,但是没有通过。 What could be the possible reason? 可能是什么原因?

function findLongestWord(str, separator) {
    var splitString = str.split(separator);
    for (var i = 1; i <= splitString.length; i++) {
        for (j = 1; j < splitString[i].length; j++) {
            while (j === ' ') {
                return j;
            }
        }
    }
    var greater;
    if (j > greater) {
        greater = j;
    }
    return greater;
}

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

Here's your code with explanation and some changes to make it work 这是您的代码,并附有说明和进行一些更改以使其正常工作

 function findLongestWord(str, separator) { var splitString = str.split(separator); // Define it as empty string var greater = ''; // Start looping from 0th index upto the length for (var i = 0; i < splitString.length; i++) { for (j = 0; j < splitString[i].length; j++) { // Don't know what this is // `j` is the index, ie number, it cannot be equal to ` ` // I guess this is confused with the separator // This can be removed without any problem while (j === ' ') { return j; } // No use code } // Here `j` is the length of the word // Compare it with the length of greater word if (j > greater.length) { // Update the greater to current `i` string greater = splitString[i]; } } // Return greater string. return greater; } var longestWord = findLongestWord("The quick brown fox jumped over the lazy dog", ' '); document.body.innerHTML = 'Longest Word: ' + longestWord; 


The same code with little optimizations can be re-written as 几乎没有优化的相同代码可以重写为

 function findLongestWord(str, separator) { var splitString = str.split(separator); // Define it as empty string var greater = ''; for (var i = 0, len = splitString.length; i < len; i++) { if (splitString[i].length > greater.length) { // Update the greater to current `i` string greater = splitString[i]; } } return greater; } var longestWord = findLongestWord("The quick brown fox jumped over the lazy dog", ' '); document.body.innerHTML = 'Longest Word: ' + longestWord; console.log(longestWord); 

My Solution using ES6 我使用ES6的解决方案

You can use Array#reduce and Arrow functions . 您可以使用Array#reduceArrow函数 For same code in ES5 check this answer by @gurvinder372 对于ES5中的相同代码,请通过@ gurvinder372检查此答案

str.split(' ').reduce((x, y) => x.length > y.length ? x : y);

 function findLongestWord(str, separator) { return str.split(' ').reduce((x, y) => x.length > y.length ? x : y); } var longestWord = findLongestWord("The quick brown fox jumped over the lazy dog", ' '); document.body.innerHTML = 'Longest Word: ' + longestWord; console.log(longestWord); 

Try this fiddle 试试这个小提琴

 function findLongestWord(str, separator) { return str.split(separator).reduce(function (previousValue, currentValue) { return previousValue.length < currentValue.length ? currentValue : previousValue; }); } var longestWord = findLongestWord("The quick brown fox jumped over the lazy dog", ' '); console.log(longestWord); document.body.innerHTML = longestWord; 

Please try this: 请尝试以下方法:

function findLongestWord(str, separator) {
    var splitString = str.split(separator);  
    var greater = splitString[0];
    for (var i = 1; i < splitString.length; i++) {
        if(greater.length < splitString[i].length){
        greater = splitString[i]
      }
    }  
    return greater;
}

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

Javascript index starts from 0 to (length-1). Javascript索引从0到(length-1)开始。 After calling the split method on 'separator' argument, the words are stored in the splitString and indexed from 0 to (length-1). 在对'separator'参数调用split方法后,这些单词将存储在splitString中,并从0到(length-1)索引。 To find the longest word, before starting the loop we may safely assume that the first word is the longest. 为了找到最长的单词,在开始循环之前,我们可以安全地假设第一个单词最长。 Then we can iterate over the words to check if any one is longer than this. 然后,我们可以遍历单词以检查是否有任何一个单词比这更长。 If we find one, we can update our longest word. 如果找到一个,我们可以更新最长的单词。 Your inner loop is redundant and the code can be write like this- 您的内部循环是多余的,可以这样编写代码:

function findLongestWord(str, separator) {
var splitString = str.split(separator);
var greater = splitString[0];
for (var i = 1; i < splitString.length; i++) {
    if(greater.length < splitString[i].length)
    {
        greater = splitString[i];
    }
}
return greater; 
}
findLongestWord("The quick brown fox jumped over the lazy dog", ' ');

NB: If there are more than one word with the longest length, using this algorithm you will always find the first one searching from left to right. 注意:如果有多个单词的长度最长,使用此算法,您将始终从左到右找到第一个搜索词。 If you want the last one just change in if condition in the loop like this- 如果您想要最后一个,只需在条件循环中更改if条件,例如:

if(greater.length <= splitString[i].length)

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

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