Adding Salaries
Page 13 in the book Algorithmics, The Spirit of Computing.
Modules 8 and 11 in Java Script, A Beginner's Guide.
For arrays, please see the
Introduction to Java Script.
A record differs from an array since it contains few data items of
different type. These are therefore referred to by names and not by
index numbers. For example, if one stores for a person the full name
and the salary it gets from the company, then the record for the
owner would contain the name "Eberhard Ei" and the number 0.00 since
he does not get a salary from his own company. Introducing a variable
owner for these data, it could be constructed using the following
constructor function:
function makeowner()
{ this.fullname = "Eberhard Ei";
this.salary = 0.00; }
The constructor function is then used in the main program with the
keyword "new" in front in order to signal that the variable receives
a new data record instead of some other values:
owner = new makeowner();
Then the following two Boolean conditions are true and the third one
is false:
owner.fullname == "Eberhard Ei"
owner.salary == 0.00
owner.salary > 3.33
Instead of creating every record with an own function, one could use
one function with parameters to create many records, this one is implemented
in this file:
function employee(fn,sl)
{ this.fullname = fn;
this.salary = sl; }
Having this function, one would then construct the record owner by the
command
owner = new employee("Eberhard Ei",0.00);
and could use the same function to construct an array containing the
data for all employees.
allemployees = new Array(4);
allemployees[0] = new employee("Anneliese Aal",1324.35);
allemployees[1] = new employee("Boris Bratling",1122.44);
allemployees[2] = new employee("Claudia Creme",4044.04);
allemployees[3] = new employee("Doris Dattel",1000.01);
The latter is implmeneted in the program of this file.
Adding the salaries is done as follows; the implementation
in this file is enriched by some "document.write"-commands which are
omitted here:
function salarysum()
{ var notednumber = 0.00; var ind;
for (ind=0;ind<allemployees.length;ind=ind+1)
{ notednumber = notednumber+allemployees[ind].salary; }
return(notednumber) }
The expression "allemployees[2].salary" would refer to the salary
of employee number 2 which is Claudia Creme. Instead of this fixed
reference, one can use the variable ind which for ind = 0,1,2,3
refers to the salaries of employees 0,1,2,3 one after the other.
So the loop does add up the salaries stored in the field
"allemployees[ind].salary" for the four employees. The entry
allemployees.length contains the length of the array allemployees,
thus one can use it as the upper bound in the for-loop. The
relevant part in main program is then introducing the variable
total and assigning the output of the function salarysum to it;
the result is written into the main window.
var total = salarysum();
document.write("<br>Total Amount is SGD "+total+".<br>");
And here the full output of the program.