导致脚本失败的方法

时间:2014-09-24 00:32:37

标签: javascript

我的方法遇到了很多麻烦。代码在没有它的情况下工作正常,但是完全无法使用它。我希望它确定两个字段是否为空。

如果有更好的方法可以做到,那么除此之外,我当然对此持开放态度。

function showPerson ( ) {   //method that fails
    if ( this.firstName != " " && this.lastName != " ") {
        document.writeln(this.lastName + "; " + this.firstName);
    } else if (this.firstName !=  " "  && this.lastName = " ") {
        document.writeln( this.firstName);
    } else  if (this.firstName = " " && this.lastName != " ") {
        document.writeln(this.lastName);
    }  else {
        document.writeln("Unknown");
    }
}

var Person = function (firstName, lastName, areaCode, phone) {   /objector constructor
    this.firstName = firstName;
    this.lastName = lastName;
    this.areaCode = areaCode;
    this.phone = phone;
    this.phoneNumber = "(" + areaCode + ")" + phone;
    this.show = showPerson; 
}

function getInfo() {    //prompts user for info
    var firstName = prompt("What is your first name: ");
    var lastName = prompt("What is your last name: ");
    var areaCode = prompt("What is your area code: ");
    var phone = prompt("What is your phone number: ");
    return new Person(firstName, lastName, areaCode, phone);
}



var user = getInfo();   //create object

user.show();            //show object

2 个答案:

答案 0 :(得分:0)

据我所知,Person.show()showPerson()都没有被调用过。那为什么要执行呢?

编辑:

您的=块中有分配==而不是比较运算符===if else

编辑2:

检查您是否确实要使用" ",我认为您需要""

我已经更改了你的代码并制作了一个jsfiddle:http://jsfiddle.net/2p34me8n/

答案 1 :(得分:0)

将其更改为:

function showPerson ( ) {   //method that fails
    if ( this.firstName != " " && this.lastName != " ") {
        document.writeln(this.lastName + "; " + this.firstName);
    } else if (this.firstName !=  " "  && this.lastName == " ") {
        document.writeln( this.firstName);
    } else  if (this.firstName == " " && this.lastName != " ") {
        document.writeln(this.lastName);
    }  else {
        document.writeln("Unknown");
    }
}

同时

我只想指出this.firstname!=“”不如this.firstname.trim()!=“”当字符串为空时它会处理更多情况......