简体   繁体   中英

My code for finding the longest word does not work

    function findLongestWord(str){
  var array = str.split(" ");
  var long = array[0].length;
  for(var i = 0; i < array.length; i++){
    if(long < array[i].length){
      long = array[i];
    }
  }
  return long;
}

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

I was already given the solution to this problem; but, I wanted to know why this program does give the longest word

Update your code to following

  • Update var long = array[0].length; to var long = array[0]; ( store value )
  • In if condition, update long < to long.length < ( compare length )

 function findLongestWord(str){ var array = str.split(" "); var long = array[0]; for(var i = 0; i < array.length; i++){ if(long.length < array[i].length){ long = array[i]; } } return long; } console.log(findLongestWord("The quick brown fox jumped over the lazy dog"));

Try this. You have to use long.length in if block.

function findLongestWord(str){
  var array = str.split(" ");
  var long = array[0];
  for(var i = 0; i < array.length; i++){
    if(long.length < array[i].length){
      long = array[i];
    }
  }
  return long;
}

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

Try this one.

 findLongestWord("The quick brown fox jumped over the lazy dog"); function findLongestWord(str) { const arr = str.split(' ').map(e => e.length); const idx = Math.max(...arr); console.log(str.split(' ')[arr.indexOf(idx)]); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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