[英]im doing a guess the number project but my if else doesn't seem to work properly. what am i doing wrong?
its not showing the first message when the results do match it only ever shows the message for when you have lost.当结果匹配时,它不会显示第一条消息,它只会在您丢失时显示消息。
I have tweaked it and it ends up being a thing where it either always says you win even though it tells you what you have guessed doesn't match我已经对其进行了调整,最终它要么总是说你赢了,即使它告诉你你猜的不匹配
JS Code JS代码
function play(){
let random = Math.floor(Math.random() * 3 + 1)
let guess = document.querySelector('#myguess').value;
let pick = document.querySelector('#pick');
if (guess.value === random){
pick.innerText = 'You picked '+guess+" the result was "+random+" Congrats!, you guessed correctly"
}
else {
pick.innerText = 'You picked '+guess+" the result was "+random+" Looks like you guessed incorrectly! Sorry :("
}
}
document.getElementById('btn').addEventListener("click", play)
html html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Guess the number</title>
<!-- stylesheet -->
<link rel="stylesheet" href="/Users/leon/Desktop/Webdevelopment/guessinggame/guessstyles.css">
<!-- global fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto+Mono&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fork-awesome/1.2.0/css/fork-awesome.min.css" integrity="sha512-aupidr80M36SeyviA/hZ2uEPnvt2dTJfyjm9y6z1MgaV13TgzmDiFdsH3cvSNG27mRIj7gJ2gNeg1HeySJyE3Q==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<!-- font awesome -->
</head>
<body>
<div class="container">
<div class="header">
<h2>Pick A Number between 1 and 3</h2>
</div>
<div class="number-area">
<input type="number" id="myguess">
<button id="btn" onclick="play()">Submit</button>
</div>
<div class="result">
<p id="pick">Let's see if you picked the correct number?</p>
</div>
</div>
</body>
<script src="/Users/leon/Desktop/Webdevelopment/guessinggame/guessindex.js"></script>
</html>
In this comparison:在这个比较中:
if (guess.value === random){
guess
is a string guess
是一个字符串guess.value
is undefined
guess.value
undefined
random
is a number random
是一个数字===
checks for type equality as well as value equality ===
检查类型相等以及值相等First of all, drop the .value
because that isn't a property on a string.首先,删除
.value
因为它不是字符串的属性。 Aside from that, you can do a weaker non-type-checking comparison:除此之外,您可以进行较弱的非类型检查比较:
if (guess == random){
Or you could convert the types, such as by parsing the string as a number:或者您可以转换类型,例如将字符串解析为数字:
if (parseInt(guess) === random){
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.