Need help on javascript book assignment on arrays

Hi,
I am extremely new to JavaScript and am currently in a class. I am having big problems understanding the assignments from the book (it is the worst book ever and doesn’t even explain what to do in the assignments). I have scanned the assignment from the book and pasted the code in they give you. Any help doing this and understanding it would be greatly appreciated. Also what would be a great book to get to use to help me understand my horrible textbook?

Assignment pages: are attached they explain what you are supposed to do.

The files they supply:

election.htm:

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<!-- 
   New Perspectives on JavaScript, 2nd Edition
   Tutorial 3
   Case Problem 2

   Congressional Election Results
   Author: 
   Date:   

   Filename:         election.htm
   Supporting files: back.jpg, logo.jpg, results.css, votes.js

--> 
   <title>Congressional Races</title>
   <link href="results.css" rel="stylesheet" type="text/css" />
    
   <script src="votes.js" type="text/javascript"></script>
   
   <script type="text/javascript">
   
   		function totalVotes() {
			
		var total = 0;
		for (vari = 0; i < votes.length; i++)  {
			
		}
		return total
		}
   
   </script>
   
</head>

<body>

   <div id="intro">
      <p><img src="logo.jpg" alt="Election Day Results" /></p>
      <a href="#">Election Home Page</a>
      <a href="#">President</a>
      <a href="#">Senate Races</a>
      <a href="#">Congressional Races</a>
      <a href="#">State Senate</a>
      <a href="#">State House</a>
      <a href="#">Local Races</a>
      <a href="#">Judicial</a>
      <a href="#">Referendums</a>
   </div>

   <div id="results">
      <h1>Congressional Races</h1>

   </div>

</body>
</html>

votes.js:


/*
   New Perspectives on JavaScript, 2nd Edition
   Tutorial 3
   Case Problem 2

   Filename: votes.js

   Variable List:

   races:           The name of the five races
   name1 - name5:   The name of the candidate for races 1 through 5
   party1 - party5: The party affliations of the candidates
   votes1 - votes5: The number of votes the candidate has received

*/

var race = new Array();

var name1  = new Array();
var name2  = new Array();
var name3  = new Array();
var name4  = new Array();
var name5  = new Array();

var party1  = new Array();
var party2  = new Array();
var party3  = new Array();
var party4  = new Array();
var party5  = new Array();

var votes1  = new Array();
var votes2  = new Array();
var votes3  = new Array();
var votes4  = new Array();
var votes5  = new Array();


race[0]="1st Congressional District";
race[1]="2nd Congressional District";
race[2]="3rd Congressional District";
race[3]="4th Congressional District";
race[4]="5th Congressional District";

name1[0]="Sarah Carlson";
party1[0]="D";
votes1[0]=45125;
name1[1]="Pete deJesus";
party1[1]="R";
votes1[1]=44498;
name1[2]="Alan Tompkins";
party1[2]="I";
votes1[2]=5143;

name2[0]="Gary Griffin";
party2[0]="D";
votes2[0]=69505;
name2[1]="Frank Brown";
party2[1]="R";
votes2[1]=78133;
name2[2]="Roland Washington";
party2[2]="G";
votes2[2]=8109;
name2[3]="Karen Reese";
party2[3]="L";
votes2[3]=13004;

name3[0]="Anne Sanchez";
party3[0]="D";
votes3[0]=65203;
name3[1]="Cynthia Thomas";
party3[1]="R";
votes3[1]=51289;

name4[0]="Jerry Wilkes";
party4[0]="D";
votes4[0]=49201;
name4[1]="Barry Mitchell";
party4[1]="R";
votes4[1]=58414;
name4[2]="Paula Welton";
party4[2]="I";
votes4[2]=3901;

name5[0]="Pete Grimbold";
party5[0]="D";
votes5[0]=42105;
name5[1]="Carol Ives";
party5[1]="R";
votes5[1]=43349;
name5[2]="Michael Dorn";
party5[2]="G";
votes5[2]=1401;

That’s all right. It’s why we get together here and discuss these things. Many people here know more about things that I do, but by bringing them together here we can all benefit.

Didn’t know it was considered “bad” to do. I do understand though that for in loop over the properties of the object. Just never really thought about it before. Just one of those things I haven’t had bite me in the ass yet to have learned from perhaps.

I quickly ran through the exercise and one thing you need to watch out for is correctly escaping the HTML strings. That is one of the major disadvantages of writing text string as HTML over manipulating the DOM using nodes. Your on the right track though with the what you have done. I copied and pasted that directly on top and everything seems to be working as expected. Also, I didn’t quite get how the bars were being created until I added a background color. You might want to add a background color to each bar field, to actually see the bars. Though, I’m guessing there is some CSS for that outlined on one of the initial pages, not presented. One thing that always helps is to constantly check whether the code is broken using an alert. Its much easier to squash bugs and prevent mistakes before they begin by using alerts every few lines and checking what has been written actually runs, is the correct syntax.

Because I’m feeling generous I’ll post the first function for you to understand the practical,programmatic application of the nomenclature.


function totalVotes(votes) {
	var total = 0;
	
	for(var x in votes) {
		total+= votes[x];
	}
	
	return total;
	
}

I don’t know I think I just got stuck with a bad teacher and a bad book. This is my first language I have worked with besides a tiny bit of action script. I don’t know if I’m just not grasping the concepts or what. Can you recommend a good book to supplement the current book I’m using. I do not want to seem like I am trying to take the easy way out. I really want to learn this but I do the walk-through tutorial in the book (which is how the teacher teaches the class) and I find that it doesn’t satisfy the requirements of the assignment. But I look at what I did following the steps and I understand why I did it. Just seeing the code written out it helps me understand the steps and why they are there.

While we do help people with their javascript problems, there are issues when it comes to homework and assignments.

Be cautious with the homework help that you receive. There are people who gain pleasure from providing the wrong answer, or a deliberately complex or “perfect” answer so that your teacher will know that it wasn’t someone just learning who came up with the solution.

Where your teacher or tutor has not done a good enough job of providing you with the information that you need to complete your assignment, you need to go back to your teacher for further assistance.

I have worked through the assignment myself, and find that what it demands is reasonable.

I do take issue with it teaching you to use single quotes to delimit HTML attributes, and for using techniques on an XHTML transitional page that are not compatible with an XHTML strict page, but I don’t know that future plans may be to help correct those issues.

Given the following type of instructions, I would say that there is nothing in this assignment that you shouldn’t have already learned, or should find out further information from the person who taught you.

declare a variable named total setting its initial value to 0.

Well, the array should only have what we expect, otherwise there is a flaw in the logic and that is something that should be accounted for outside the function or generation of the function in the first place. I’m generally one to decorate objects rather than augment them directly. So I guess its never been a problem for me, though I see what your saying.

Look carefully at the error message, for it is not “document” that is undefined, but a sightly different mis-spelling of it that has been used instead.

So I am stuck again. I went through the instructions and nothing writes. Firebug just lists one error on line 65 saying that document is undefined. Any guidance with this would be appreciated. Thank you.

<?xml version=“1.0” encoding=“UTF-8” ?>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=“http://www.w3.org/1999/xhtml”>

<!–
New Perspectives on JavaScript, 2nd Edition
Tutorial 3
Case Problem 2

Congressional Election Results
Author:
Date:

Filename: election.htm
Supporting files: back.jpg, logo.jpg, results.css, votes.js

–>
<title>Congressional Races</title>
<link href=“results.css” rel=“stylesheet” type=“text/css” />

<script src=“votes.js” type=“text/javascript”></script>

<script type=“text/javascript”>

	function totalVotes() {
		
	var total = 0;
	var i;
	for (i = 0; i &lt; votes.length; i += 1) {
	 total += votes[x];
	}
	return total
	alert(total);
	}
	
	
	function calcPercent(item, sum) {
		return Math.round((item/sum)*100);
		alert(calcPercent (item, sum));		
	}
	
	function createBar(partyType, percent) {
		switch (partyType) {
			case "D" : barText = "&lt;td class = 'dem'&gt;&lt;/td&gt;";
				break;
			case "R" : barText = "&lt;td class = 'rep'&gt;&lt;/td&gt;";
				break;
			case "I" : barText = "&lt;td class = 'ind'&gt;&lt;/td&gt;";
				break;
			case "G" : barText = "&lt;td class = 'green'&gt;&lt;/td&gt;";
				break;
			case "L" : barText = "&lt;td class = 'lib'&gt;&lt;/td&gt;";
				break;
			for (var i = 1; i&lt;percent ; i++) {
				document.write(bartext);
			}
		}
		
	}
		function showResults(race, name, party, votes) {
			var totalV=votes;
			doument.write("&lt;h2&gt; race &lt;/h2&gt;");	
			doument.write("&lt;table cellspacing='0'&gt;");
			doument.write("&lt;tr&gt;");
			doument.write("&lt;th&gt;Candidate&lt;/th&gt;");
			doument.write("&lt;th class = 'num'&gt;Votes&lt;/th&gt;");
			doument.write("&lt;th class = 'num'&gt;%&lt;/th&gt;");
			doument.write("&lt;/tr&gt;");
			
			for (i=0; i&lt;name.length; i++) {
				document.write("&lt;tr&gt;");
				document.write("&lt;td&gt;name (party)&lt;/td&gt;");
				document.write("&lt;td class = 'num'&gt;votes&lt;/td&gt;");	
				
				var percent = calcPercent(votes, totalV);
				document.write("&lt;td class = 'num'&gt;(percent%)&lt;/td&gt;");
				
				createBar(party, percent);
				
				document.write("&lt;/tr&gt;");
			}
			document.write("&lt;/table&gt;");
		}

</script>

</head>

<body>

<div id=“intro”>
<p><img src=“logo.jpg” alt=“Election Day Results” /></p>
<a href=“#”>Election Home Page</a>
<a href=“#”>President</a>
<a href=“#”>Senate Races</a>
<a href=“#”>Congressional Races</a>
<a href=“#”>State Senate</a>
<a href=“#”>State House</a>
<a href=“#”>Local Races</a>
<a href=“#”>Judicial</a>
<a href=“#”>Referendums</a>
</div>

<div id=“results”>
<h1>Congressional Races</h1>
<script type= “text/javascript”>
showResults(race[0], name1, party1, votes1);
showResults(race[1], name2, party2, votes2);
showResults(race[2], name3, party3, votes3);
showResults(race[3], name4, party4, votes4);
showResults(race[4], name5, party5, votes5);
</script>

</div>

</body>
</html>

Thank you for your help, I finally got it to work.

As long as it’s remembered that for…in iterates over all of the properties of an object.

Many code conventions state that iterating over arrays should not be performed using for…in. It’s just one of those “good practices” that helps to prevent future problems.

I must advise that you should not use for…in when processing arrays. The for…in iterates over all of the properties and methods that may be prototyped on to the array as well, so the safest and best way to process an array is to use the standard for statement


var i;
for (i = 0; i < votes.length; i += 1) {
    total += votes[x];
}

I won’t go to the point of quoting all examples, because they are nearly identical, but I have not come across any code conventions that state anything different from what follows:

Code Conventions for the JavaScript Programming Language

The first form should be used with arrays and with loops of a predeterminable number of iterations.

The second form [for…in] should be used with objects. Be aware that members that are added to the prototype of the object will be included in the enumeration.

Google JavaScript Style Guide

Only for iterating over keys in an object/map/hash

for-in loops are often incorrectly used to loop over the elements in an Array. This is however very error prone because it does not loop from 0 to length - 1 but over all the present keys in the object and its prototype chain.

Specifically what exactly are you not understanding? I just read over the assignment and it all seems pretty straight-forward, just follow the steps.