我正在尝试为一周中的几天创建一个数组,但如果输入的数字未分配给值,我希望它显示错误。这就是我所拥有的,但它在我的if语句之后说“今天未定义”。我认为这是因为阵列。有没有办法把if语句作为数组的一部分,所以只弹出一条消息?
var dayNum=prompt('enter as number from 0 to 6', ' ');
if (dayNum >='7');
{
alert("invalid input received, try again")
}
var weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", " "];
alert("Today is " + weekdays[dayNum]);
答案 0 :(得分:4)
因为分号在这里终止了陈述
if (dayNum >='7');
删除分号。此外,如果输入无效,则第二种情况仍在运行。而是将其放入else语句中。
var dayNum = Number( prompt('enter as number from 0 to 6', ' ') );
if ( isNaN(dayNum) || dayNum >= 7 )
{
alert("invalid input received, try again")
} else {
var weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
alert("Today is " + weekdays[dayNum]);
}

最后,将字符串(这是提示的返回类型)转换为数字类型然后将它们视为一个类型也是明智之举。在这种情况下,JavaScript知道数组的索引只能是一个数字,因此会自动尝试为您转换类型。只要用户键入有效数字,就可以将其用作索引而不会出现问题。但是,字符串按字母顺序进行比较。这意味着(string >= '7')
可能并不总是按照您的预期行事:字母大于数字,但特殊字符较少。
答案 1 :(得分:0)
;
if (dayNum >=7)
var dayNum=prompt('enter as number from 0 to 6', ' ');
if (dayNum >=7)
{
alert("invalid input received, try again")
}
var weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", " "];
alert("Today is " + weekdays[dayNum]);
document.getElementById("demo").innerHTML = weekdays[dayNum];
答案 2 :(得分:0)
您的代码中几乎没有错误。首先是在if条件之后的分号,而另一个是使用字符串比较而不是数字。在if条件中从数字中删除引号。并且数组的索引也是错误的。你提供一个字符串。它应该是int类型。
<script>
var dayNum=parseInt(prompt('enter as number from 0 to 6', ' '));
if (dayNum >= 7)
{
alert("invalid input received, try again");
}
else{
var weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", " "];
alert("Today is " + weekdays[dayNum]);
}
</script>
答案 3 :(得分:0)
实际上,如果你使用0,你会希望输入为1-7,并且要声明一个假错误:
var weekdays = ["Error", "Sun", "Mon", ..., "Sat"];
然后你需要创建一个循环来将字符串转换为数字:
for(i=0;i<=7;i++){
if(dayNum==i){
dayNum=i;
}
}
这将使用近似值为您提供整数而不是字符串。你的钓鱼代码如下:
var dayNum=prompt('enter as number from 0 to 6', ' ');
for(i=0;i<=7;i++){
if(dayNum==i){
dayNum=i;
}
}
if (dayNum <=7)
{
alert("invalid input received, try again");
}
else if(dayNum === 0)
{
alert("invalid input received, try again");
}
else
{
var weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", " "];
alert("Today is " + weekdays[dayNum]);
}
答案 4 :(得分:0)
var dayNum=prompt('enter as number from 0 to 6', ' ');
for(i=0;i<=7;i++){
if(dayNum==i){
dayNum=i;
}
}
if (dayNum >=7)
{
alert("invalid input received, try again");
}
else if(dayNum === 0)
{
alert("invalid input received, try again");
}
else
{
var weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", " "];
alert("Today is " + weekdays[dayNum]);
}
&#13;