Jump to content
Larry Ullman's Book Forums
krompir

Chapter 6 Review And Pursue

Recommended Posts

For the last exercise in review and pursue: "If you’re feeling particularly confident, combine the techniques demonstrated in tasks.js and employee.js so that an array of employee objects is created." (p. 218).

 

How does one proceed to create an array of objects? I am quite lost. Most of my attempts have resulted in [object Object] being returned or an ordered list listing each object element under a new list item. The original code is:

 

 

 

 

 

// employee.js
// This script creates an object using form data.

// Function called when the form is submitted.
// Function creates a new object.
function process() {
'use strict';

// Get form references:
var firstName = document.getElementById('firstName').value;
var lastName = document.getElementById('lastName').value;
var department = document.getElementById('department').value;

// Reference to where the output goes:
var output = document.getElementById('output');

// Create a new object:
var employee = {
firstName: firstName,
lastName: lastName,
department: department,
hireDate: new Date()
}; // Don't forget the semicolon!

console.log(employee);

// Create the ouptut as HTML:
var message = '
[b]	Employee Added[/b]

Name: ' + employee.lastName + ', ' + employee.firstName + '
';
message += 'Department: ' + employee.department + '
';
message += 'Hire Date: ' + employee.hireDate.toDateString();

// Display the employee object:
output.innerHTML = message;

// Return false:
return false;

} // End of process() function.

// Initial setup:
function init() {
'use strict';
document.getElementById('theForm').onsubmit = process;
} // End of init() function.
window.onload = init;

Share this post


Link to post
Share on other sites

An array of objects is essentially just that: an array in which each element is an object, as opposed to a more conventional array, which might hold only numbers or strings.

 

One important thing to note in JS is that arrays are technically objects. More accurately, an array is a predefined subset of the Object class with a preset index.

As a result, if you put an object within an array and alert the array to the screen, you will see "object Object", with the lowercase "object" referring to the array.

 

With that said, without even looking at your code, I can say that it may in fact be working correctly, but the way you're alerting it to the screen doesn't make that obvious at all.

Try alerting more specific values to the screen and see what happens. For example, if you have 10 objects in an array and each object has a property called "speed", then you can alert the various speed properties to the screen as follows:

 

// Assume that the array variable containing the objects is called arr.

for (i = 0; i < 10; i++) {

 alert(arr[i].speed);

}

  • Upvote 1

Share this post


Link to post
Share on other sites

I have done as you suggested and the elements in the array are being displayed. However, with each new item added the first item is deleted, displaying only the last item, instead of an ordered list.

 

 

 // create a new object
var employee = {
firstName: firstName,
lastName: lastName,
department: department,
hireDate: new Date(),
getName: function(){
return this.lastName + ', ' + this.firstName;
}
};

// add items to an array
newHires.push(employee.firstName);

// create output as HTML
for (var i = 0, counter = newHires.length; i < counter; i++) {
var message = '
[b]	Employee Added:[/b]
[list=1]
';
message += '	[*]' + newHires[i] + '
';
}
message += '
[/list]
';

// display the employee object
output.innerHTML = message;

Share this post


Link to post
Share on other sites

I figured it out. I placed the var message containing the opening tag of the ordered list within the for loop, creating a new list each time.

Thank you for your help.

  • Upvote 1

Share this post


Link to post
Share on other sites

I'm a bit confused with exactly what this question is asking me to do. I'm looking at the solution above and it does not quite make sense to me. In the code above a new object is created named var employee. This appears to be the only object created. Don't I need to create several objects in order to create an array out of them? Can someone please explain what I am missing. Thanks!

Share this post


Link to post
Share on other sites

From what I can tell, the main purpose of the tasks.js script is to show you how to add elements onto the end of an array.

For the employee.js script, it seems like the main purpose is to create a new employee object every time the relevant data is entered into the form and the form is submitted.

 

So I guess the idea of the last question is to combine the two scripts so that every time you create a new employee object, that object is added onto the end of an array that contains other employee objects.

As for krompir's code above, I cannot comment on whether it works or not, as I have not actually tested it out. I guess we'll just have to take his word for it.

Share this post


Link to post
Share on other sites

So it looks like HartleySan is adding an object with one element to an array:

newHires.push(employee.firstName);

I would like to add the entire employee object including all of it's elements. I'm thinking I would do that with:

newHires.push(employee);

When I use

alert(employees[0].firstName);

it works but when I try

alert(employees[1].firstName);

I get nothing. Any suggestions?

Share this post


Link to post
Share on other sites

It probably doesn't work because once you have pushed the employee object into the newHires array, you should be using the newHires array to reference the various values. For example, let's imagine the following objects:

 

var employee1 = {

 first_name: 'Bob',

 last_name: 'Smith',

 age: 48

};

var employee2 = {

 first_name: 'Pam',

 last_name: 'Brown',

 age: 32

};

var employee3 = {

 first_name: 'Joe',

 last_name: 'Schmoe',

 age: 22

};

 

Next, let's push all of these employee objects into an array called newHires as follows:

 

var newHires = []; // The array is empty at the moment.

newHires.push(employee1);

newHires.push(employee2);

newHires.push(employee3);

 

Now, we could alert info to the screen as follows:

 

alert(newHires[0].first_name); // Alerts 'Bob'.

alert(newHires[1].first_name); // Alerts 'Pam'.

alert(newHires[2].age); // Alerts 22.

alert(newHires[0].age); // Alerts 48.

alert(newHires[1].last_name); // Alerts 'Brown'.

 

And so on and so forth.

Does that clarify any confusion you may have?

  • Upvote 2

Share this post


Link to post
Share on other sites

My array is actually named employees. I forgot to change it when I copied and pasted the code above. Sorry about that. My function is working. What I was doing wrong was trying to send an alert before the object existed in the array. I put the alert in an if statement and it works. Thanks for your advice. Again sorry about the confusion.

Share this post


Link to post
Share on other sites

It probably doesn't work because once you have pushed the employee object into the newHires array, you should be using the newHires array to reference the various values. For example, let's imagine the following objects:

 

var employee1 = {

first_name: 'Bob',

last_name: 'Smith',

age: 48

};

var employee2 = {

first_name: 'Pam',

last_name: 'Brown',

age: 32

};

var employee3 = {

first_name: 'Joe',

last_name: 'Schmoe',

age: 22

};

 

Next, let's push all of these employee objects into an array called newHires as follows:

 

var newHires = []; // The array is empty at the moment.

newHires.push(employee1);

newHires.push(employee2);

newHires.push(employee3);

 

Now, we could alert info to the screen as follows:

 

alert(newHires[0].first_name); // Alerts 'Bob'.

alert(newHires[1].first_name); // Alerts 'Pam'.

alert(newHires[2].age); // Alerts 22.

alert(newHires[0].age); // Alerts 48.

alert(newHires[1].last_name); // Alerts 'Brown'.

 

And so on and so forth.

Does that clarify any confusion you may have?

 

I have been wondering myself as to when these objects would be used in your web pages with javascript, most of my stuff would be handled server side via PHP. I saw a marketplace web site called Buzzmart.com, if you make an account with them and go to their item listing it all works in javascript, i could see the js objects fitting nicely into a situation like that where all the product data could be held within an object. If you don't have Javascript enabled with Buzzmart you can't even register with them, its a hardcore js site.

Share this post


Link to post
Share on other sites

I suppose that's the way things are headed. Within a year or two, IE6 and IE7 will no longer be supported, at which point, if you don't have an HTML5-enabled browser, you'll be missing out on a lot. Likewise, I imagine a lot of sites will require the use of Javascript. Personally, I'm not too crazy about this trend, but what can you do? That's the site developer's situation, so long as the business acknowledges that a JS-only site could potentially hurt business.

 

Edit: Edward, just out of curiosity, I went to buzzmart.com with and without JS, and it was fine either way. Without JS, the little bird didn't fly around, but other than that, the site was fine.

Share this post


Link to post
Share on other sites

Last time i disabled JS on Buzzmart i wasn't able to even register, its possible they have updated the site since then, i was there probably 6 months ago. Anyway all round i think its quite a good website, in terms of functionality there isn't much but its a good starting point.

Share this post


Link to post
Share on other sites

I wanted to add its practically impossible now to make a descent web site these days without javascript. I think with most of the main sites on the market, there will be some part of the site where you can't operate if you don't have javascript enabled in your browser. My site also would be inoperable without js at parts, so i think the best solution is that if someone does not have js use and alert message to tell the user that he must have javascript enabled in order to view the page with full functionality. Lets face it we are pretty much past the days of PHP only websites, that's great news by the way of the upcoming death of IE6 and IE7, awesome.

Share this post


Link to post
Share on other sites

Yeah, I agree, but I still like the idea of a PHP-only site. Perhaps it's antiquated thinking on my part. Plus, I've heard (although I can't verify the validity of this) that Web crawlers still can't reliably read JS and in order to maximize SEO (which I still question the validity of as a whole), everything must be reachable sans JS.

Share this post


Link to post
Share on other sites

I thought Twitter only works if you have Js enabled and its one of the worlds most popular sites. The seo you are talking about on sites makes little or no difference everyone's site will do that so how can one be picked out from another. Seo works best from articles posted only, blogs, press releases, social bookmarking etc, youtube video's whatever. The more of those key things you have done for your site the more traffic you will drive in. Also the sites are ranked by how long they are active. That's probably why our friend Buzzmart is struggling right now, it needs more time to get overall traffic.

Share this post


Link to post
Share on other sites

A PHP only site would be nice but for examples there are also cases like if you need a drop down menu to appear you can do this by css only but its ugly, its just much easier to use jquery or js alone to bring out an invisible div and then disable it, the js way is much neater and logical than messing around with css. I think if you want a descent site these days you have to move forward and use js, like i mentioned already just an alert at the top of the screen to indicate this page needs js to function probably is fine. Jesus we got kids here at 5 years old that its there 2nd nature to use an iphone, people really need to be getting there act together if they don't even have a browser with JS, what are we going to do hold there hands for ever or is time for them to grow up?

Share this post


Link to post
Share on other sites

Well, I agree that for most sites these days, it's essential to use JS, but it doesn't hurt to also have a non-JS site for... yeah, someone, I guess.

I don't know. I'm weird like that, I guess. I wonder if anyone has ever gone to a single site I've designed/helped designed without JS enabled, but yet, I still feel obligated to design a non-JS version, all the same.

I suppose I'll get over it one of these days.

Share this post


Link to post
Share on other sites

I suppose that's the way things are headed. Within a year or two, IE6 and IE7 will no longer be supported, at which point, if you don't have an HTML5-enabled browser, you'll be missing out on a lot. Likewise, I imagine a lot of sites will require the use of Javascript. Personally, I'm not too crazy about this trend, but what can you do? That's the site developer's situation, so long as the business acknowledges that a JS-only site could potentially hurt business.

 

Edit: Edward, just out of curiosity, I went to buzzmart.com with and without JS, and it was fine either way. Without JS, the little bird didn't fly around, but other than that, the site was fine.

 

"Unfortunately the one browser that doesn't have addEventListener() is...Internet Explorer, prior to version 9." They forgot to add IE8 to the garbage list, may be one of us could give them a call to remind them. ;)

Share this post


Link to post
Share on other sites

Yeah, IE8 does suck. We'll be stuck with that one for a while though.

At least it supports most HTML5 features.

 

I have to admit though, IE9 isn't bad. Dare I say that there are even a few things that I like about it?

I still prefer Chrome and FF over IE9, but it's not a bad attempt by Microsoft.

Share this post


Link to post
Share on other sites

Hi, 
 
 I don't know if anyone's still watching this thread, but I'm stumped.  I've been working through this book sequentially without any problems up until this last 'review and pursue' task 'combine employee.js and tasks.js to create a list of employees'. I understand the concept, but what I can't figure out, after much effort, is how to create a new object. Or rather - I can create a new object, but each time I try to add it to the 'newHires' array, it deletes the previous, and the 'newHires.length' returns '1'. 
 
   I've gone through the above many times, read the relevant chapter sections again, looked at the code in tasks.js again and again - but don't understand why the following code doesn't work. Any help appreciated as I really want to figure this out and feel it's something simple I'm missing.  
 
   Great book Larry - been trying many javascript/ programming resources over the years, this is the first one that really sticks, both for javascript and the concepts of programming generally. 

 

    function process() {
    'use strict'; 
 
    //Get a reference for the HTML elements
    var firstName = document.getElementById('firstName').value; 
    var lastName = document.getElementById('lastName').value; 
    var department = document.getElementById('department').value; 
 
    //Get a reference for the output
    var output = document.getElementById('output'); 
 
 
    //Create a new object, representing the employee
   var employee = {
        firstName: firstName,  
        lastName: lastName,  
        department: department,
        hireDate: new Date() 
    }; //End of object
 
    var newHires=[]; 
 
    console.log(employee.firstName);
 
    newHires.push(employee.firstName);
 
    console.log(newHires); 
 
    console.log(newHires.length); 
 
 
    //Main problems seems to be here - employee objects not being added to the array - 'employees.length' returns '1'  each time. 
 
 
    // Attempt at separating objects with a loop
    /*for (var i = 0, counter = newHires.length; i < counter; i++) {
            //Add items to an array
            console.log(newHires.firstName); 
    };*/
 
    //Display the output
    //output.innerHTML = message; 
 
    //Return false to prevent submission
    return false; 
}//end function
 
  
 
   Thanks, 
 
   Tim

Share this post


Link to post
Share on other sites

Tim, welcome to the forums, and in the future, please put your code within code tags (by using the button that looks like <>),

 

I'm not sure if there is other code you're not showing me, but here are the things I noticed:

 

1) The following line in your code is reinitializing the newhires array each time, which essentially makes it an empty array:

var newHires=[]; 

Basically, you don't want to do that. I'd recommend placing that line of code above somewhere outside of the process function so that it's only executed once, when the program starts.

More than likely, that is the main issue with your code, but I'm not sure. Please try it.

 

2) You placed a semicolon at the end of your for loop. You don't need that, and actually, it's a syntax error. Please delete it.

 

3) The following line is commented out, but still, I don't see the message variable being declared anywhere, so be careful about that:

//output.innerHTML = message; 

Well, that's all I can think of for now.

Please let us know whether that helps or not.

Thanks.

  • Upvote 1

Share this post


Link to post
Share on other sites

This is my solution to the last question in CH6 review and Pursue:  If you’re feeling particularly confident, combine the techniques demonstrated in tasks.js and employee.js so that an array of employee objects is created.

 

I'm not really sure if what console.log()  shows on google-chrome is the correct solution

here is the javascript code, name it   solution.js :


//need a global array of Employees outside of the function
var Employees = [];

function process() {
    'use strict';
    // Get form references:
    var firstName = document.getElementById('firstName').value;
    var lastName = document.getElementById('lastName').value;
    var department = document.getElementById('department').value;

    // Reference to where the output goes:
    var output = document.getElementById('output'); 
    var empnum = document.getElementById('empnum');

    // Create a employee object:
    var employee = {
            firstName : firstName,
	    lastName  : lastName,
	    department: department,
	    hireDate  : new Date()
	}; 

    // Add the employee object to the Employees array:
    Employees.push(employee);
    console.log('these are the employee objects:'); // look on chrome console
    console.log(Employees); // chrome console Employees Objects

    // Create the ouptut as HTML:
    var message = '<h2>Employee Added</h2>Name: ' + employee.lastName + ', ' + employee.firstName + '<br>';
    message += 'Department: ' + employee.department + '<br>';
    message += 'Hire Date: ' + employee.hireDate.toDateString();
    
    // Display the employee object:
    output.innerHTML = message;
    // display the employee count:
    empnum.innerHTML = 'You have ' + Employees.length + ' Employees';
        
    return false;
    
} 

// Initial setup:
function init() {
    'use strict';
    document.getElementById('theForm').onsubmit = process;
} 
window.onload = init;

Here is the HTML :

<!doctype html>
<html lang="en">
<head>
	<!-- combine the techniques demonstrated in tasks.js and employee.js so that an array of employee objects is created.  -->

    <meta charset="utf-8">
    <title>Employee Form</title>
    <!--[if lt IE 9]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <link rel="stylesheet" href="css/form.css">
</head>
<body>
	<form action="#" method="post" id="theForm">
	    <fieldset><legend>Add an Employee</legend>
	        <div><label for="firstName">First Name</label><input type="text" name="firstName" id="firstName" required></div>
	        <div><label for="lastName">Last Name</label><input type="text" name="lastName" id="lastName" required></div>
	        <div><label for="department">Department</label><select name="department" id="department">
	            <option value="Accounting">Accounting</option>
	            <option value="Administration">Administration</option>
	            <option value="Human Resources">Human Resources</option>
	            <option value="Marketing">Marketing</option>
	        </select></div>
	        <input type="submit" value="Submit" id="submit">
	    </fieldset>
	    <div id="output"></div>
	    <div id="empnum"></div>
	</form>
    <script src="js/solution.js"></script>
</body>
</html>

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...