2017-05-18 10 views
1

誰かが私にここで間違っていることを教えてもらえますか?テストケース(console.log(longestWord( "what is the hell is going on"))としてこれを入力すると、最も長い単語として '戻ってくる'という結果が得られます...テストしたケース...その狂気私を助けてくださいドライブ。ありがとうございました!!!javascriptで一番長い単語を見つけて返す

function longestWord(string) { 
var words = string.split(' '); 

for (var i = 0; i < words.length; i++) { 
    var currentWord = words[i]; 

    var longestWord = words[0]; 

    if (longestWord.length < currentWord.length) { 
     longestWord = currentWord; 
    } 
} 
return longestWord; 
} 

答えて

1

あなたはループの反復ごとに、あなたの最も長い単語をリセットした。その後、ループの実行前に初期(最初の)最も長い単語を設定し、それがされます正常に動作。

function longestWord(string) { 
 
    var words = string.split(' '); 
 
    
 
    // Set the intial longest word out here 
 
    var longestWord = words[0]; 
 
    // Need to loop through from index 1 
 
    for (var i = 1; i < words.length; i++) { 
 
    var currentWord = words[i]; 
 
    
 
    // Setting the longest word to the initial word here means that it will set the longest word to be "what" everytime your loop runs. 
 
    
 
    if (longestWord.length < currentWord.length) { 
 
     longestWord = currentWord; 
 
    } 
 
    } 
 
    return longestWord; 
 
} 
 

 
console.log(longestWord("What the hell is going on"));

+0

ループを 'i = 1'で開始してください。すでに 'longestWord'に入っているので、要素0をテストする必要はありません – Barmar

1

ヨルダンはあなたに正しい答えを与えました。また、ソート機能を使用すると、次のように最初の要素を返すことができます。

function longestWord(string) { 
 
    var words = string.split(' '); 
 
    return words.sort(function (a, b) { return b.length - a.length; })[0]; 
 
} 
 

 
console.log(longestWord("what the hell is going on"))

0

私はES6ワンライナーを投稿し、念のため...

let longestWord = str => str.split(' ').sort((a, b) => b.length - a.length)[0]; 
 

 
console.log(longestWord("what the hell is going on"));

関連する問題