I'm trying to create an array of objects for an assignment in Javascript, but the following doesn't seem to work
var employee = {
employeeId: "",
hoursWorked: 0,
overtimeWorked: 0,
wage: 15
};
var employees = [];
var p = 0;
var i = 0;
while(p != -1){
p = prompt("please enter employee id#")
employees[i] = new employee();
employees[i].employeeId = p;
i++
}
I've gone through and comment debugged my code and the problem seems to be
employees[i] = new employee();
Whether or not I do this outside the loop, or with any element in the array, I don't seem to be able to instantiate any elements of the array as the employee object.
2 Answers 2
You can only use new with a constructor function. So, you need to change your employee variable into a constructor function.
function Employee() {
this.employeeId = "";
this.hoursWorked = 0;
this.overtimeWorked = 0;
this.wage = 15;
};
Then, you can do:
employees[i] = new Employee();
and get a new employee object each time.
In your specific case, I'd suggest allowing the constructor to take an argument too and fixing up your while loop to handle cancel of the user prompt appropriately:
function Employee(id) {
this.employeeId = id;
this.hoursWorked = 0;
this.overtimeWorked = 0;
this.wage = 15;
};
var employees = [];
var p = 0;
while (true) {
p = prompt("please enter employee id#");
if (!p) {
break;
}
employees.push(new Employee(p));
};
Working demo: http://jsfiddle.net/jfriend00/zk7bdfrv/
FYI, your while loop was flawed too because prompt() returns null when cancelled, not -1 and you were using the null value.
3 Comments
Define employee as the following :
function Employee() {
this.employeeId = "";
this.hoursWorked = 0;
this.overtimeWorked = 0;
this.wage = 15;
};
Then instantiate as :
new Employee();
It is a best practice to name your constructor functions with an uppercase first letter. That way, they differ from other objects and you know you can instantiate them.
new: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…