我正在创建对象类型为Employee的数组,但是其中一个属性无法正常工作。

我使用的是Employee类型的对象数组,这些对象是通过构造函数语句块定义的。构造函数的一部分是,如果未定义昵称属性,则将名字用作昵称。另外,如果未定义移位,则将其设置为“ 1”。

当我调试时,我会看到总是对昵称和shift进行设置,就好像为这些属性未定义任何内容一样,即使它们没有定义。是什么赋予了?

详细信息:在Win7机器上的IE9上运行,也使用jquery2.1。

这是代码:

// make sure doc ready first
$(document).ready(function(){
    function Employee(firstname, lastname, nickname, employeeID, shift, serviceTruck, pickupTruck, serviceTruckWO){
        this.firstname = firstname;
        this.lastname = lastname;
        /*
         * Check if the nickname is present. If not,
         * set as lastname. Credit to SO for
         * how to do this properly, ref
         * http://stackoverflow.com/questions/27509/detecting-an-undefined-object-property-in-javascript
         */
        if (typeof this.nickname === "undefined") {
            this.nickname = this.firstname;
        }
        else {
            this.nickname = nickname;
        }
        this.employeeID = employeeID;
        if (typeof this.shift === "undefined") {
            this.shift = "1";
        }
        else {
            this.shift = shift;
        }
        this.serviceTruck = serviceTruck;
        this.pickupTruck = pickupTruck;
        this.serviceTruckWO = serviceTruckWO;
    }
    var Employees = new Array();
    Employees[0] = new Employee("John", "Smith", "Smithy", "1234", "2", "ST1", "PU1", "WO1");
    Employees[1] = new Employee("Jane", "Doe", "", "1235", "", "ST2", "PU2", "WO2");

});

最佳答案

在设置this.nickname之前,请先对其进行检查,以便其类型仍未定义。

if (typeof nickname === "undefined") {
        this.nickname = this.firstname;
    }
    else {
        this.nickname = nickname;
    }

关于javascript - JavaScript对象构造函数数组未按预期工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24042091/

10-12 00:24
查看更多