2017-02-01 6 views
0

"気分キーワード"に基づいて動機付けの引用を表示するウェブページを作成しています。string.includes forループの最後の値をチェックするjavascript

私は配列を持つオブジェクトがあります。

const moodList = { 
sad: [ 
    '"Dream as if you\'ll live forever, live as if you\'ll die today." James Dean', 
    '"Life is a journey, and if you fall in love with the journey, you will be in love forever." Peter Hagerty', 
    '"I\'ve learned that people will forget what you said, people will forget what you did, but people will never forget how you made them feel." Maya Angelou' 
], 
angry: [ 
    '"For every minute you remain angry, you give up sixty seconds of peace of mind."Ralph Waldo Emerson', 
    '"Speak when you are angry - and you\'ll make the best speech you\'ll ever regret." Laurence J. Peter', 
    '"Anger and intolerance are the enemies of correct understanding."Mahatma Gandhi' 
]} 

を、これは私が配列を持つオブジェクトに対するユーザー入力をチェックするために書いているコードです。一致があると、その特定の配列からランダムな動機付けの引用が表示されます。しかし、else文を書くと、なぜオブジェクトの中の最後の配列だけが考慮されていますか?

for (let key in moodList) { 
    const moodFeeling = key; 
    if (askBar.value.includes(moodFeeling)) { 
    for (let i = 0; i <moodList[moodFeeling].length; i += 1) { 
     motivQuoteResult.push(moodList[moodFeeling][i]); 
     const randomResult = Math.floor(Math.random() * motivQuoteResult.length); 
     printToPage(motivQuoteResult[randomResult]); 
    } 
    } else { 
    printToPage('<h3>Try again, I don\'t have that feeling on file</h3>'); 
    } 
} 

motivQuoteResult = []; 

askBar.value = ''; 
} 
}); 
+0

を私は "悲しい" のためのelse文を毎回取得します。 「怒っている」は正しく動作します。 – Amos

+0

コードがありませんか?スニペットの最後に余分なコーディングカッコがあるようです... – Pineda

+0

申し訳ありませんが、余分なコードはありません。私はこれを初めて知っており、コードを正しく貼り付ける方法を考え出していません。 – Amos

答えて

0

イムあなたがユーザの入力や「悲しい」などのユーザーのタイプのものをチェックしていると仮定。あなたは、私はあなたがいない場合は、ループ内で他の何かをしたいと思います

let possibleMoods = Object.keys(moodList).filter(mood => askbar.value.indexOf(mood) > -1); 
let moodQuotes = possibleMoods.map(mood => moodList[mood]); 
if(moodQuotes.length === 0) { 
    ... no mood found do something else 
} 
let possibleQuotes = moodQuotes[Math.random()*possibleQuotes.length]; 
if(possibleQuotes.length === 0) { 
    ... no quotes found for mood, do something else 
} 
printToPage(possibleQuotes[Math.floor(Math.random()*possibleQuotes.length)]) 
0

askbar.valueが利用可能に気分のいずれかだけでこれを使用するが含まれている必要がある場合

let moodQuotes = moodList[askBar.value]; 
if(Array.isArray(moodQuotes) && moodQuotes.length) { 
    printToPage(moodQuotes[Math.floor(Math.random()*moodQuotes.length)]) 
} 
else { 
    ... no quote found do something else 
} 

: は、このコードを試してみてくださいループも必要ありません。そして私はあなたが何をしたいのかわからないmotivQuoteResult。私はただそれを残す。実際には他の配列の各要素を新しい配列にプッシュする必要はありません。このコードを試してみて、ウル目的として変更:

var askBarValue = askBar.value; 
    var hasMoodOnFile = false; 
    for (let key in moodList) { 
      const moodFeeling = key; 

      var motivQuoteResult = []; 
      if (askBar.value.includes(moodFeeling)) { 
        motivQuoteResult = moodList[moodFeeling]; 
       var randomResult = Math.floor(Math.random() * motivQuoteResult.length); 
       result.innerHTML = motivQuoteResult[randomResult];// call your printToPage function instead 
       hasMoodOnFile = true; 
      } 
    } 
    if(!hasMoodOnFile){ 
      result.innerHTML = '<h3>Try again, I don\'t have that feeling on file</h3>'; // call your printToPage function instead 
    } 

これは、ソースコードである: https://jsfiddle.net/85dxus4z/

0

あなたのロジックが構成されている方法を使用すると、いずれかで(あなたのループの各反復で「printToPage」と呼びます「if」ブランチまたは「else」ブランチ)。 printToPageがDOM要素の内容を上書きしている場合は、最後の反復の結果のみが表示されます。これを修正する方法はたくさんありますが、ループの前にブール変数(たとえばfoundMatch)をfalseに初期化し、if文でtrueに設定する方法もあります。 elseを取り除く。その後、ループの後に: (!foundMatch)を検索するための

+0

優れた観察ありがとうございました。 – Amos

0

{あなたの「もう一度やり直してください」というメッセージを印刷}場合は、小文字(使用toLowerCasekeyが小文字textに含まれているかどうかを確認するためにindexOfを使用する必要があります。

は怒鳴る例でI'm so sad right now!のようなものを試してみて、入力します。

const moodList = { 
 
    sad: [ 
 
    '"Dream as if you\'ll live forever, live as if you\'ll die today." James Dean', 
 
    '"Life is a journey, and if you fall in love with the journey, you will be in love forever." Peter Hagerty', 
 
    '"I\'ve learned that people will forget what you said, people will forget what you did, but people will never forget how you made them feel." Maya Angelou' 
 
    ], 
 
    angry: [ 
 
    '"For every minute you remain angry, you give up sixty seconds of peace of mind."Ralph Waldo Emerson', 
 
    '"Speak when you are angry - and you\'ll make the best speech you\'ll ever regret." Laurence J. Peter', 
 
    '"Anger and intolerance are the enemies of correct understanding."Mahatma Gandhi' 
 
    ] 
 
}; 
 

 

 
var askBar = prompt("Ask bar:"); // for the sake of this example I'm using prompt 
 

 
var printToPage = alert; // for the sake of this example I'm using alert instead of your printToPage 
 

 
// to see if we found something or not 
 
var found = false; 
 

 
for (let key in moodList) { 
 
    // change askBar to askBar.value 
 
    if (askBar.toLowerCase().indexOf(key.toLowerCase()) != -1) { 
 
    var randomIndex = Math.floor(Math.random() * moodList[key].length); 
 
    printToPage(moodList[key][randomIndex]); 
 
    found = true; // we found something 
 
    break; // don't search anymore so terminate the loop 
 
    } 
 
} 
 

 
// now if we are outside the loop and we've found nothing 
 
if (!found) 
 
    printToPage('Try again! I don\'t have that feeling on file!');

+0

これは非常にうまくいきます!しかし、includeの代わりにindexofを使うのはなぜですか? - 私も含めての例を作りましたし、それをやっているようです? また、どのように各キーの内側の配列に到達していますか?私はこれがforループを使って反復することしかできないと思いましたか? – Amos

+0

@Amos私は 'indexOf'を使って検索することに慣れています。おそらく 'インクルード'もそれを使うでしょう。 –

+0

@Amosあなたが違いについてもっと知りたいなら[this](http://stackoverflow.com/questions/35370222/array-prototype-in​​cludes-vs-array-prototype-in​​dexof)をチェックしてください! –

関連する問題