2017-04-03 55 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