繁体   English   中英

将字符串转换为数组后查找字符串中最长的单词

[英]Finding the longest word in a string, after converting it to an array

我是 javascript 开发的新手,目前正在努力完成免费代码训练营及其挑战/项目。

我被要求写一个 function 来找出字符串中最长的单词:“The quick brown fox jumped over the lazy dog”。 这是我执行此操作的代码:

function findLongestWordLength(str) {

  let result = 0;                // define result value of 0
  str.split(" ");                // split string into array, separated by spaces
  for(let i = 0; i < str.length; i++) {     // for loop to iterate through each index of array
  let counter = 0;                          // counter equals 0
  counter += str[i].length;     // counter equals to itself + length of the ith index in array
  if(counter > result) {        // if counter is greater than result then result = counter
    result = counter;
  }   
 } 
return result;
}

我确信有很多比我正在做的更好的方法来做到这一点,我可以简单地寻找一种不同的/更好的方法来做到这一点并解决这个问题。 但是,与其忽略错误并转向不同的方法,我想先从中吸取教训,然后也许我会以不同的方式解决问题。 如果有人能向我指出这一点,我真的很高兴,这样我就可以从错误中吸取教训,无论我哪里出错了。

如果有人还想建议其他可能更有效的方法,请告诉我,我很想了解更多解决这些问题的方法:)

你把事情搞得太复杂了。 您无需计算任何内容,只需比较字符串的长度并跟踪最长的字符串即可。

 var x = "The big brown fox jumped over a bee."; var arr = x.split(" "); var biggest = arr[0]; for (i = 1; i < arr.length; i++) { if (arr[i].length > biggest.length) biggest = arr[i]; } console.log(biggest);

在您的代码中,您只运行str.split(" "); 但是您没有将结果存储回str

在比较中,您必须检查循环中的当前长度是否大于您已经存储在结果中的长度。

如果它更大,则将其设置为新的最大值。

您可以将代码更新为

 function findLongestWordLength(str) { let result = 0; // init current result to 0 const arr = str.split(" "); // store the splitted string in arr as array (naming it str is not clear anymore in the code) for (let i = 0; i < arr.length; i++) { // loop the arr array const len = arr[i].length // for every item in the array, get the string length if (len > result) { // if the string length here is greater than the one in result result = len; // set result to the new maximum length } } return result; // at the end of the loop, return the maximum } console.log(findLongestWordLength("The quick brown fox jumped over the lazy dog"));

我会这样做,一行:

 const input = "The quick brown fox jumped over the lazy dog"; const longestWord = sentence => sentence.split(" ").map(word => word.length).sort().pop(); console.log(longestWord(input))

解释:

sentence
     .split(" ") // [ "The", "quick", "brown" ...... ]
     .map(word => word.length) // [ 3, 5, 5, 3, 6, 4, 3, 4, 3]
     .sort() // [3, 3, 3, 3, 4, 5, 5, 6]
     .pop(); // 6

split为一个数组,按长度对元素进行排序,然后pop最后一个元素。

 function findLongestWordLength(str) { const arr = str.split(' '); return arr.sort((a, b) => a.length - b.length).pop(); } console.log(findLongestWordLength('The quick brown fox jumped over the lazy dog'));

 const string = "this is a test String" function longestWord(str) { let arr = str.split(" ") let result = arr.reduce((acc,val)=> acc.length>val.length?acc:val,"") console.log(result) } longestWord(string)

它有 2 种输入任何代码的方法。

初学者可以理解的方式:

function findLongestWordLength(str) {
    let result = { 'str_count': 0, 'str_count': '' };
    str = str.split(" ");
    for (let i = 0; i < str.length; i++) {
        if (i + 1 < str.length) {
            if (str[i].length > result['str_count']) {
                result['longest_str'] = str[i];
                result['str_count'] = str[i].length;
            }
        }
    }
    return result;
}
console.log(findLongestWordLength("The quick brown fox jumped over the lazy dog"));

以及推进者疯狂的方式:

var result = { 'str_count': 0, 'longest_str': '' };
'The quick brown fox jumped over the lazy dog'.split(' ').forEach(word => {
    result['str_count'] = Math.max(result['str_count'], word.length);
    result['longest_str'] = (result['longest_str'].length >= word.length ? result['longest_str'] : word);
    console.log(result);
});

执行2种方式:

 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1:0"> <title>Document</title> </head> <body> <script> function findLongestWordLength(str) { let way_1 = { 'str_count', 0: 'str_count'; '' }. str = str;split(" "); for (let i = 0. i < str;length. i++) { if (i + 1 < str.length) { if (str[i];length > way_1['str_count']) { way_1['longest_str'] = str[i]. way_1['str_count'] = str[i];length; } } } return way_1. } console;log(findLongestWordLength("The quick brown fox jumped over the lazy dog")): // -------------------------------- var way_2 = { 'str_count', 0: 'longest_str'; '' }. 'The quick brown fox jumped over the lazy dog'.split(' ').forEach(word => { way_2['str_count'] = Math,max(way_2['str_count']. word;length). way_2['longest_str'] = (way_2['longest_str'].length >= word?length: way_2['longest_str']; word); }). console;log(way_2); </script> </body> </html>

暂无
暂无

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

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