简短的Javascript程序问题(错误输出)

时间:2014-10-12 19:20:19

标签: javascript if-statement

const HIGH_AGE = 70, MAX_AGE = 120, BABIE_AGE=4, TEEN_AGE=16;

function main ()

{

 var age;  
    age = Number(prompt('Enter your age:')); //set prompt box ask user's age

    if (age < BABIE_AGE || age > MAX_AGE)//if user user's age are below "0" or above "120" 
        alert('Please Enter Age Within the Range between 0-120!');//output: must enter age in valid age range

    else if (isNaN(age) == true || !age)
        alert('please enter a valid entry');   

    else if ((age >= HIGH_AGE) || (age >= 0 && age <= BABIE_AGE))//if age between 0-4 or above 70 
        alert('You may travel for free');//output: they can travel for free     

    else if (age >= CHILDREN_AGE && age <= TEEN_AGE )//if user's age are under 16 
        alert('You may travel with a half price ticket');//output they can travel for half-price

    else 
        alert('You must travel with a full price ticket'); //others all travel with full price
}

4 个答案:

答案 0 :(得分:1)

只需检查它是否为数字:

age = prompt('Enter your age:');

if (age == +age) alert("Please insert a number!");
else {
    // do what you want
}

答案 1 :(得分:1)

使用isNaN功能:

if (isNaN(age)) {
    // ... age is not valid number
}

Number(prompt('...'))如果无法将输入解释为数字,则会返回NaN值。

答案 2 :(得分:0)

快速而肮脏的解决方案(我能想到的唯一一个快速解决方案)是使用parseInt(); 我希望这会有所帮助。

答案 3 :(得分:0)

我刚编辑了你的功能。你可以尝试一下。

const HIGH_AGE = 70, MAX_AGE = 120, BABIE_AGE=0, CHILDREN_AGE=4, TEEN_AGE=16;

function main () { 

var age;

    while(/^(?:[1-9]+(?:[0-9]+)?|0)$/.test((age = prompt('Enter your age:'))) == false) {
    alert("You must enter number!");
}

age = Number(age);

if (age < BABIE_AGE || age > MAX_AGE)//if user's age are below "0" or above "120" 
    alert('Please enter age within the range between 0-120!');//output: must enter age in valid age range

else if ((age >= HIGH_AGE) || (age >= BABIE_AGE && age <= CHILDREN_AGE))//if age between 0-4 or above 70 
    alert('You may travel for free');//output: they can travel for free

else if (age >= CHILDREN_AGE && age <= TEEN_AGE )//if user's age are under 16 
    alert('You may travel with a half price ticket');//output they can travel for half-price

else 
    alert('You must travel with a full price ticket'); //others all travel with full price      

}

看看这段代码:

while(/^(?:[1-9]+(?:[0-9]+)?|0)$/.test((age = prompt('Enter your age:'))) == false) {
    alert("You must enter number!");
}

这是工作jsfiddle: http://jsfiddle.net/zono/varrwx32/14/