繁体   English   中英

年龄计算器:检查空白输入或字符串输入

[英]Age calculator: checking for a blank input or a string input

我有一个功能,问您一些问题来确定您的年龄。 我想取消该功能并在用户输入字符串值或根本不输入任何内容时发出警报。

到目前为止,这是我的代码:

<button id="btn"> Calculate Age </button>

<p id="para"></p>


document.getElementById("btn").addEventListener("click", ageCalc);


function ageCalc () {

    // Calculate year of birth

    var year = prompt("What year were you born?");
    if (parseInt(year) < 1917) {
        return alert("Please enter a valid year");
    }

    // Calculate month of birth

    var month = prompt("Numerically, what month were you born?");

    if (parseInt(month) > 12 || parseInt(month) < 1 ) {
        return alert("Please enter a valid month!");
    }


    // Calculate day of birth

    var day = prompt("What day were you born?");

    if(parseInt(day) > 32 || parseInt(day) < 1) {
        return alert("Please enter a valid day!");
    }

    // Calculate age based on user input

    var presentDate = new Date ();
    var birthDate = new Date(year,month,day);
    var age = (presentDate - birthDate) / 1000 / 60 / 60 / 24 / 365;

    return document.getElementById("para").innerHTML = "You are " + Math.floor(age) + " years old.";
}

这是什么适当的举动? 我认为它将以某种方式调整if语句以检查字符串或空白语句,但是我有点迷失了。 有什么想法吗?

您可以通过简单地添加if检查来排除空/未定义/空year值。 另外,请始终为parseInt方法添加第二个radix参数:

var year = prompt("What year were you born?");
if (!year || parseInt(year, 10) < 1917) {       
   return alert("Please enter a valid year");
}

您可以在monthday执行相同的操作。

    document.getElementById("btn").addEventListener("click", ageCalc);


    function ageCalc () {

// Calculate year of birth

        var year = prompt("What year were you born?");
        if (parseInt(year) < 1917) {
            return alert("Please enter a valid year");
        }
        else if (year == null)
            return;

// Calculate month of birth

        var month = prompt("Numerically, what month were you born?");

        if (parseInt(month) > 12 || parseInt(month) < 1 ) {
            return alert("Please enter a valid month!");
        }
        else if (month == null)
            return;


// Calculate day of birth

        var day = prompt("What day were you born?");

        if(parseInt(day) > 32 || parseInt(day) < 1) {
            return alert("Please enter a valid day!");
        }
        else if (day == null)
            return;

// Calculate age based on user input

        var presentDate = new Date ();
        var birthDate = new Date(year,month,day);
        var age = (presentDate - birthDate) / 1000 / 60 / 60 / 24 / 365;

        return document.getElementById("para").innerHTML = "You are " + Math.floor(age) + " years old.";
    }

只需通过检查输入结果是否不是NaN来检查使用parseInt()时输入是否正确解析:

if( parseInt(month) == NaN ){ alert("invalid input"); return false; }

如果用户键入一个非int可解析的输入,它将停止执行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM