我正在创建一个 Employee 对象类型的数组,但其中一个属性未按预期工作。
我正在使用 Employee 类型的对象数组,该数组是通过构造函数语句 block 定义的。构造函数的一部分是,如果没有定义昵称属性,则使用名字作为昵称。另外,如果未定义移位,则将其设置为“1”。
当我调试时,我发现昵称和类次总是设置为好像没有为这些属性定义任何内容,即使它们是这样。给出了什么?
详细信息:在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 对象构造函数数组未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24042091/