2017-04-03 6 views
1

このif文はelseブロックであり、どちらもforループ内にあります。これを実行すると、常にif文とelse文の両方の値が返されます。 if文がfalseのときにelseブロックに行くべきではありませんか?代わりに、オブジェクトの上にループを作成するのではなく、あなたが入力した値がオブジェクトのキーであるかどうかを確認することができJavascript for..Inループif文とelse文の両方を実行します。

<!DOCTYPE html> 
 
<html> 
 
<body> 
 

 
<p>Click the button to begin</p> 
 

 
<button onclick="myFunction()">Try it</button> 
 

 
<script> 
 

 
const moodList = { 
 
    sad: { 
 
     quotes: ['this is a sad quote', 
 
       'this is a sad quote number 2', 
 
       'this is a sad quote number 3' 
 
       ] 
 
    }, 
 
    happy: { 
 
     quotes: ['this is a happy quote', 
 
       'this is a happy quote number 2', 
 
       'this is a happy quote number 3' 
 
       ] 
 
    } 
 
} 
 

 
function myFunction() { 
 

 
    let moodInput = prompt('Enter a feeling'); 
 

 
    for (var key in moodList) { 
 
    if (moodInput.includes(key)) { 
 
     console.log('you got a result!'); 
 
    } else { 
 
     console.log('nothing'); 
 
    } 
 
    } 
 
} 
 
</script> 
 

 
</body> 
 
</html>

+0

そうではありません。なぜあなたはそれがだと思いますか?それが同時に両方を行う方法はありません。それは、ループの異なる反復中にそれぞれを実行しているかもしれませんが、それは異なっています。 – Utkanos

+0

各キーをループしています。私が悲しいことを入力した場合、あなたは一度真実になり、一度あなたのIFになるでしょう。 – yBrodsky

+0

あなたはあなたのmoodList上でループを実行しています - すべての可能性に対してユーザーの入力をチェックします - 入力したものであればすべてのmoddに記録されます – Danmoreng

答えて

2

if (moodList[moodInput]) { 
    console.log('you got a result!'); 
} else { 
    console.log('nothing'); 
} 

更新されたコード:

const moodList = { 
 
    sad: { 
 
    quotes: ['this is a sad quote', 
 
     'this is a sad quote number 2', 
 
     'this is a sad quote number 3' 
 
    ] 
 
    }, 
 
    happy: { 
 
    quotes: ['this is a happy quote', 
 
     'this is a happy quote number 2', 
 
     'this is a happy quote number 3' 
 
    ] 
 
    } 
 
} 
 

 
function myFunction() { 
 
    let moodInput = prompt('Enter a feeling'); 
 
    if (moodList[moodInput]) { 
 
    console.log('you got a result!'); 
 
    } else { 
 
    console.log('nothing'); 
 
    } 
 
}
<p>Click the button to begin</p> 
 

 
<button onclick="myFunction()">Try it</button>

1

キーを使用して、キーがオブジェクト内にあるかどうかをin operatorで確認できます。

const moodList = { 
 
    sad: { 
 
     quotes: ['this is a sad quote', 
 
       'this is a sad quote number 2', 
 
       'this is a sad quote number 3' 
 
       ] 
 
    }, 
 
    happy: { 
 
     quotes: ['this is a happy quote', 
 
       'this is a happy quote number 2', 
 
       'this is a happy quote number 3' 
 
       ] 
 
    } 
 
}; 
 

 
function myFunction() { 
 
    let moodInput = prompt('Enter a feeling'); 
 

 
    if (moodInput in moodList) { 
 
     console.log('you got a result!'); 
 
    } else { 
 
     console.log('nothing'); 
 
    } 
 
}
<p>Click the button to begin</p> 
 
<button onclick="myFunction()">Try it</button>

+0

大変感謝しています!私は絶対初心者であり、使用するタイミングとループを使用しないタイミングを忘れないようにしています。あなたの例はすばらしいおかげです。 – Amos

関連する問題