如果在满足凭据时语句未执行

时间:2014-10-15 20:04:09

标签: javascript if-statement

我试图制作一个简单的代码来检查用户输入的电话号码是否格式正确,但是当满足所有三个凭据时我的if语句将不会执行,它只会打印& #34;请输入电话号码......"或者是空白屏幕,即使我正确输入了数字。

    var phonenumber=prompt("What is your phone number?", "");
var firstdash=phonenumber.charAt(3);
var seconddash=phonenumber.charAt(7);
var length=phonenumber.length;
if(firstdash=='-' && secondash=='-' && length==12)
    {document.write("Your phone number is "+phonenumber+", thank you.");}
else
    {document.write("Please type the phone number in the proper format (555-555-1234)");}

3 个答案:

答案 0 :(得分:4)

seconddash在您的情况下拼写错误,您错过了第二个d - 在开发时始终打开控制台..您会看到:

Uncaught ReferenceError: secondash is not defined 

答案 1 :(得分:2)

seconddash声明中应该secondash而不是if



var phonenumber=prompt("What is your phone number?", "");
var firstdash=phonenumber.charAt(3);
var seconddash=phonenumber.charAt(7);
var length=phonenumber.length;
if(firstdash=='-' && seconddash=='-' && length==12)
    {document.write("Your phone number is "+phonenumber+", thank you.");}
else
    {document.write("Please type the phone number in the proper format (555-555-1234)");}




答案 2 :(得分:2)

我可以推荐一种不同的方法吗?如果您只是检查数字格式是否正确,请使用正则表达式:

var phoneNumber = prompt("What is your phone number?", "");
if(isValidPhoneNumber(phoneNumber)) {
    document.write("Your phone number is "+ phoneNumber +", thank you.");
} else {
    document.write("Please type the phone number in the proper format (555-555-1234)");
}

function isValidPhoneNumber(phoneNumber)
{
    return /^\d{3}-\d{3}-\d{4}$/.test(phoneNumber);
}