gpt4 book ai didi

javascript - 年龄计算器 : checking for a blank input or a string input

转载 作者:行者123 更新时间:2023-12-03 04:42:16 25 4
gpt4 key购买 nike

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

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

<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 检查来排除 null/未定义/空 year 值。另外,始终为 parseInt 添加第二个radix 参数。方法:

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

您可以对执行相同的操作。

关于javascript - 年龄计算器 : checking for a blank input or a string input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43036572/

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