不能得到两个if else语句工作?检查字符串和数字

Cant not get two if else statements to work? checking strings and numbers

本文关键字:工作 语句 检查 字符串 数字 else if 两个 不能      更新时间:2023-09-26

我想运行这两个if else语句,但我不能让它们工作?请帮助。

  1. 如果输入失败,返回开始并重新询问。

    function table(){
        var num = prompt("please enter any number");
        if (num <= 0 && typeof num != 'string') {
            alert("invalid number or Zero") ;
            table();
        } else {
            alert("ok") ;
        }
    }
    table();
    
  2. 如果不正确,返回开始并重新询问。

    function text(){
        var txt = prompt("please enter rock or scissors or paper");
        if (txt != "rock" || "scissors" || "paper") {
            alert("failed") ;
            table();
        } else {
            alert("ok") ;
        }
    }
    text();
    

谢谢。

prompt返回的typeof结果将始终"string"(用户单击确定或按Enter)或"object"(用户单击取消或按Esc),因为typeof null"object"prompt返回输入的内容,或取消null。这就是第一个if的问题所在。

如果空格不可接受,则简单检查为!:

var num = prompt(...);
if (!num) {
    // User clicked Cancel or didn't type anything
}

…然后使用+numnum转换为一个数字,或者使用parseInt(num, 10)这样做,如果你想确保基数10并忽略数字之后的任何文本(parseInt("42foo", 10)42而不是NaN;+"42foo"NaN).

第二个if的问题是,您必须重复您正在测试的内容,并使用&&而不是||:

if (txt != "rock" && txt != "scissors" && txt != "paper"){

"如果txt不是石头,txt不是剪刀和…"

switch可能在这里有用:

switch (txt) {
    case "rock":
    case "scissors":
    case "paper":
        alert("ok") ;
        break;
    default:
        alert("failed") ;
        table();
        break;
}

试试下面的语法:

var num = parseInt( prompt("please enter any number") );
if (num <= 0) {
  // ...
}

第二种情况:

var txt = prompt("please enter rock or scissors or paper");
if (txt != "rock" && txt != "scissors" && txt !=  "paper") {
  // ...
}