导致脚本失败的方法

Method causing script to fail

本文关键字:方法 失败 脚本      更新时间:2023-09-26

我的方法有很多问题。没有它,代码可以很好地工作,但有了它,代码就完全失败了。我想让它确定任何一个字段是否为空。

如果有比If Else更好的方法,我当然对此持开放态度。

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

将其更改为:

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");
    }
}

此外:

我只想指出这一点。首先"不如这个。firstname.trim()!="当字符串为空时,它会处理更多的情况。。。

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

编辑:

您在if else块中分配了=,而不是比较运算符=====

编辑2:

检查一下你是否真的想使用" ",我想你想要""

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