gpt4 book ai didi

javascript - 无法检查空字符串和 null 的提示

转载 作者:行者123 更新时间:2023-12-02 22:04:36 27 4
gpt4 key购买 nike

这是我的代码:

    let guessTheNumber = () => {
let randomNumber = Math.round((Math.random()) * 10); //generating a random number from 1 to 10
console.log(randomNumber); //added this just to see what number was generated
let question = +prompt('Please, try to guess the number from 1 to 10!'); // by using unary plus I want prompt to return a number, NOT a string
if (question === randomNumber) {
alert('Wow, you are quite lucky. Nice job!'); //this one works
}
else if (question !== randomNumber) {
alert('Nope'); //this one is also easy to check
}
else if (question === "") {
alert('You did not enter anything!');
}
else {
alert('Why did you cancel?');
}
}
guessTheNumber();

question等于randomNumber变量时,我可以成功检查它。但是,当我尝试提醒某些内容时,如果存在空字符串(单击“确定”而不输入任何内容)或 null(单击“取消”),则程序将失败。

最佳答案

提示符之前的(+)convert the response to a Number因此,如果用户取消或将提示留空,它将始终返回 0

因此,如果您需要检查取消,则需要删除(+),然后提示将返回一个字符串null,因此您需要一些额外的逻辑。

let guessTheNumber = () => {
// using 'Math.ceil' as @symlink mentioned
let randomNumber = Math.ceil((Math.random()) * 10);
console.log(randomNumber);
let question = prompt('Please, try to guess the number from 1 to 10!');

// check for cancel 'null'
if (question == null) {
alert('Why did you cancel?');
// you need to exit so it won't prompt again
return
}
// parseInt() function parses a string argument and returns an integer
else if (parseInt(question, 10) === randomNumber) {
alert('Wow, you are quite lucky. Nice job!');
}
// empty value
else if (question === '') {
alert('You did not enter anything!');
// run again
guessTheNumber();
}
// not a number
else if (isNaN(question)) {
alert('Please enter a number');
// run again
guessTheNumber();
}
// wrong answer
else {
alert('Nope!')
// run again
guessTheNumber();
}
}
guessTheNumber();

关于javascript - 无法检查空字符串和 null 的提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59755452/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com