0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Bonfire: Find the Longest Word in a String

Posted at

課題内容

strを引数としてとりその中で一番文字数がある単語をその単語の数で返してくれる関数を作る。

/*
Return the length of the longest word in the provided sentence.

Your response should be a number.
*/


function findLongestWord(str) {
  return str.length;
}

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

ということで大半をこの辺から持ってきてしまいましたが(笑)

function findLongestWord(str) {
  str = str.split(' ');
  var longest = 0;
  for (var i=0; i < str.length; i++) { // str.length = # of words in "" = 9
    if (longest < str[i].length) {
      longest = str[i].length;
    }
  } return longest;
} 

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

簡単な流れを解説すると、

  1. strに"The quick brown fox jumped over the lazy dog"が入る。
  2. .split(' ')で各単語がstr配列に入る。
  3. longest = 0, i = 0
  4. i < str.lengthにしたのはiはカウンターとして置いていて配列の各単語を巡回する。つまりその回数=str.lengthが最大なので、i = str.lengthになるまで(9回)以下を実行しろということ。
  5. longest(初期値は0)と各単語を比べてもしlongestのほうが短かった場合はその単語の数をlongestがコピーするイメージ。str[i].lengthとfor loopのi=0で処理毎にi++を使えば確かに単語を一個一個見ていくことが出来ると納得。
  6. #5をひたすら繰り返して一番大きい単語の数は全ての処理が終わった後に返してくれる。

Screen Shot 2015-12-17 at 5.11.31 PM.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?