我在Code.org AppLab上有个抛硬币模拟器。(为了清楚起见,它是在JavaScript中。)有一个文本输入框,用户可以在其中输入所需的翻转次数,然后单击它下面的按钮。我想让这段代码检查输入是否不是数字,所以我使用了isNaN...
onEvent("button2","click",function(){
if (getNumber("text_input1") == isNaN) {
setText("text_area1","Please enter an integer.");
} else {
while ((flipCt < Math.abs(getNumber("text_input1")))) {
flipVal = randomNumber(0, 1);
flipCt++;
if (flipVal == 1) {
headcount++;
headstreak++;
if (headstreak > hscount) {
hscount = headstreak;
}
tailstreak = 0;
} else {
tailcount++;
tailstreak++;
if (tailstreak > tscount) {
tscount = tailstreak;
}
headstreak = 0;
}
}
setText("VERY LONG LINE OF CODE, so I deleted it for this post."));
}
});所以..。第二行是我的问题。我似乎不能让它正确地检查NaN -如果我输入一个非数字的值,它总是跳到"else“部分,并将其设为0。有什么建议吗?
发布于 2020-05-19 00:17:44
isNan的语法错误。您需要使用isNaN(getNumber("text_input1"))。如果是Nan,则返回true,否则返回false
发布于 2021-04-20 07:11:31
您也可以尝试
onEvent("button2","click",function(){
if (!getNumber("text_input1").includes(1,2,3,4,5,6,7,8,9) { /// make sure to put the "!"
setText("text_area1","Please enter an integer.");
} else {
while ((flipCt < Math.abs(getNumber("text_input1")))) {
flipVal = randomNumber(0, 1);
flipCt++;
if (flipVal == 1) {
headcount++;
headstreak++;
if (headstreak > hscount) {
hscount = headstreak;
}
tailstreak = 0;
} else {
tailcount++;
tailstreak++;
if (tailstreak > tscount) {
tscount = tailstreak;
}
headstreak = 0;
}
}
setText("VERY LONG LINE OF CODE, so I deleted it for this post."));
}
});这将让它检查text_input1中是否没有任何数字。否则,它将运行您其余的代码。
https://stackoverflow.com/questions/59687604
复制相似问题