- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我的代码:
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/
我正在尝试创建一个程序,其中字符串的前三个字符重复给定次数,如下所示: foo('Chocolate', 3) # => 'ChoChoCho' foo('Abc', 3) # => 'AbcAbcA
我有以下字符串: std::string str = "Mode:AAA:val:101:id:A1"; 我想分离一个位于 "val:" 和 ":id" 之间的子字符串,这是我的方法: std::st
DNA 字符串可以是任意长度,包含 5 个字母(A、T、G、C、N)的任意组合。 压缩包含 5 个字母(A、T、G、C、N)的 DNA 字母串的有效方法是什么?不是考虑每个字母表 3 位,我们可以使用
是否有一种使用 levenstein 距离将一个特定字符串与第二个较长字符串中的任何区域进行匹配的好方法? 例子: str1='aaaaa' str2='bbbbbbaabaabbbb' if str
使用 OAuth 并使用以下函数使用我们称为“foo”(实际上是 OAuth token )的字符串加密 key public function encrypt( $text ) { // a
我是一名优秀的程序员,十分优秀!