Array not working

T

Treetop

I cannot get this array to work. I want to have the game listed until the
day after the event, then come off the list.


function events() {

var today = new Date();
var dayarray=new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat")
var montharray=new
Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec
")

document.write('<table>');

var hockey=new Array();

hg[11]=new Array("2004/01/30 23:59:59","DES MOINES");
hg[10]=new Array("2004/01/31 23:59:59","CEDAR RAPIDS");
hg[9]=new Array("2004/02/06 23:59:59","SIOUX CITY");
hg[8]=new Array("2004/02/20 23:59:59","RIVER CITY");
hg[7]=new Array("2004/02/21 23:59:59","ST LOUIS");
hg[6]=new Array("2004/02/25 23:59:59","SIOUX CITY");
hg[5]=new Array("2004/02/27 23:59:59","WATERLOO");
hg[4]=new Array("2004/02/28 23:59:59","LINCOLN");
hg[3]=new Array("2004/03/05 23:59:59","DANVILLE");
hg[2]=new Array("2004/03/06 23:59:59","GREEN BAY");
hg[1]=new Array("2004/03/09 23:59:59","DES MOINES");
hg[0]=new Array("2004/03/19 23:59:59","LINCOLN");

for (var i=hg.length-1;i>=0;i--)
{
var event = hg[1]
var date = new Date(hg[0])
var year = 1900 + date.getYear()%1900 // < AD 3800
var cdate=dayarray[date.getDay()]+", "+montharray[date.getMonth()]+"
"+date.getDate()+" "+year+" "
if (today.getTime() <= date.getTime()) {
document.write('<tr><td valign=top>' + cdate + '</td><td>- ' + event +
'</td></tr>');
}
}

document.write('</table>');

}
 
L

Lee

Treetop said:
I cannot get this array to work. I want to have the game listed until the
day after the event, then come off the list.


You create an array named "hockey", and never use it.
You try to use an array named "hg", that you've never created.

var hockey=new Array();

hg[11]=new Array("2004/01/30 23:59:59","DES MOINES");
 
T

Treetop

Thanks, it works now, I renamed hockey to hg

Is there a way to limit how many times it runs? I would like to limit it to
5 lines displayed if possible.




Lee said:
Treetop said:
I cannot get this array to work. I want to have the game listed until the
day after the event, then come off the list.


You create an array named "hockey", and never use it.
You try to use an array named "hg", that you've never created.

var hockey=new Array();

hg[11]=new Array("2004/01/30 23:59:59","DES MOINES");
 
L

Lee

Treetop said:
Thanks, it works now, I renamed hockey to hg

Is there a way to limit how many times it runs? I would like to limit it to
5 lines displayed if possible.

var moreToShow=5;
if (moreToShow && (today.getTime() <= date.getTime())) {
document.write('<tr><td valign=top>'
+ cdate + '</td><td>- ' + event
+'</td></tr>');
moreToShow--;
}
 
T

Treetop

after I posted this, I tried some crazy ideas and one of them worked. I
created a varible (ct) and gave it a value of 1. I put an if statement that
if my var (ct) was less than or equal to 5 to process the next if statement.
In the second if statement I added one to my varible. The code worked on
both IE and Netscape. [I am posting this in case any fellow rookies wants
to know what I was thinking]


var ct = 1;
var hg=new Array();

hg[27]=new Array("2003/10/24 23:59:59","ST LOUIS");
<snip>
hg[0]=new Array("2004/03/19 23:59:59","LINCOLN");

for (var i=hg.length-1;i>=0;i--)
{
var event = hg[1]
var date = new Date(hg[0])
var year = 1900 + date.getYear()%1900 // < AD 3800
var cdate=dayarray[date.getDay()]+", "+montharray[date.getMonth()]+"
"+date.getDate()+" "+year+" "
if (ct <= 5) {
if (today.getTime() <= date.getTime()) {
ct = ct + 1
document.write('<tr><td valign=top>' + cdate + '</td><td> ' + event +
'</td></tr>');
}
}
}
 
D

Dr John Stockton

JRS: In article <[email protected]>,
seen in news:comp.lang.javascript said:
I cannot get this array to work. I want to have the game listed until the
day after the event, then come off the list.


function events() {

var today = new Date();
var dayarray=new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat")
var montharray=new
Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec
")

document.write('<table>');

var hockey=new Array() // try spelling hockey as hg ************

hg[11]=new Array("2004/01/30 23:59:59","DES MOINES");
hg[10]=new Array("2004/01/31 23:59:59","CEDAR RAPIDS");
hg[9]=new Array("2004/02/06 23:59:59","SIOUX CITY");
hg[8]=new Array("2004/02/20 23:59:59","RIVER CITY");
hg[7]=new Array("2004/02/21 23:59:59","ST LOUIS");
hg[6]=new Array("2004/02/25 23:59:59","SIOUX CITY");
hg[5]=new Array("2004/02/27 23:59:59","WATERLOO");
hg[4]=new Array("2004/02/28 23:59:59","LINCOLN");
hg[3]=new Array("2004/03/05 23:59:59","DANVILLE");
hg[2]=new Array("2004/03/06 23:59:59","GREEN BAY");
hg[1]=new Array("2004/03/09 23:59:59","DES MOINES");
hg[0]=new Array("2004/03/19 23:59:59","LINCOLN");

for (var i=hg.length-1;i>=0;i--)
{
var event = hg[1]
var date = new Date(hg[0])
var year = 1900 + date.getYear()%1900 // < AD 3800
var cdate=dayarray[date.getDay()]+", "+montharray[date.getMonth()]+"
"+date.getDate()+" "+year+" "
if (today.getTime() <= date.getTime()) {
document.write('<tr><td valign=top>' + cdate + '</td><td>- ' + event +
'</td></tr>');
}
}

document.write('</table>');

}


With that correction, it seems to work.

When continuing a topic, follow-up to the previous thread.

Do not allow your newsreader to wrap code; anyone who wants to test it
has the bother of unwrapping it. Break the months list after June, and
the other two long lines after the third (?) plus. Put a couple of
spaces after the break.

The lines that set event, year & cdate can be put within the "if".

Twice, .getTime() is not needed.

That output date format looks horribly untidy in a column in at least
one browser.

You convert every hg[0] to a Date Object; it would be more efficient
to convert new Date() to a string in the same format.

Instead of 23:59:59, you could use 24:00:00.

I assume the text strings are places. If they are not all on the same
time zone as the page user, you *may* need a high-level re-think.

Code should be indented to show intended structure; this applies to your
conditionally-written line, and to the whole contents of the loop.
 
T

Treetop

I want to thank everyone for their help with my coding - Lee, Dr John Stockton, and Hendrik Krauss.
My code is now working very well, however I want to learn why it is working and how to code
properly.

Do not allow your newsreader to wrap code; anyone who wants to test it
has the bother of unwrapping it.

I just made the correction in my new reader, thanks for the tip.

Break the months list after June, and

Do you mean just hitting enter after June or what is the proper way to break a line?

the other two long lines after the third (?) plus. Put a couple of
spaces after the break.

What are the plus signs (+) for in that line. It seems like non needed characters to me.

The lines that set event, year & cdate can be put within the "if".

I am still new to the javascript world. I posted below, the code I am currently using. I am
affraid that I do not know how to incorporate these elements into the if statement.

Twice, .getTime() is not needed.

Not sure where you mean it is not needed.

You convert every hg[0] to a Date Object; it would be more efficient
to convert new Date() to a string in the same format.


How do I do this?
I assume the text strings are places. If they are not all on the same
time zone as the page user, you *may* need a high-level re-think.

The exact time is not critical with this site.

Code should be indented to show intended structure; this applies to your
conditionally-written line, and to the whole contents of the loop.

I am new to JavaScript as I said above. I would love to learn the proper way to code, which is why
I came here. In the past I have found a free script somewhere and changed it enough to work,
however I never really understood what it was doing. For example the line

for (var i=hg.length-1;i>=0;i--)

I have no idea what it does, except that it must be the loop command. I am guessing:
The i appears to be the count or number after the hg[
It must stop when the count hits 0



The following is my exact code except for taking out 28 lines from my array to make the list
shorter.

----------------------------------

function events() {

var today = new Date();
var dayarray=new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat")
var montharray=new Array("Jan","Feb","Mar","Apr","May","Jun",
"Jul","Aug","Sep","Oct","Nov","Dec")

document.write('<table border bgcolor="ffffff" cellpadding="3">');
document.write('<tr><td><center><b>DATE</b></center></td><td><center><b>OPPONENT</b></center></td></
tr>');

var ct = 1;

var hg=new Array();

hg[1]=new Array("2004/03/09 23:59:59","DES MOINES");
hg[0]=new Array("2004/03/19 23:59:59","LINCOLN");

for (var i=hg.length-1;i>=0;i--)
{
var event = hg[1]
var date = new Date(hg[0])
var year = 1900 + date.getYear()%1900 // < AD 3800
var cdate=dayarray[date.getDay()]+", "+montharray[date.getMonth()]+" "+date.getDate()+" "+year+" "
if (ct <= 5) {
if (today.getTime() <= date.getTime()) {
ct = ct + 1
document.write('<tr><td valign=top>' + cdate + '</td><td> ' + event + '</td></tr>');
}
}
}

document.write('</table>');

}
 
R

Richard Cornford

I just made the correction in my new reader, thanks for the tip.

But did you make the right correction? Having adjusted the line wrapping
to what looks like about 100 characters the text in your post is now
coming out in a form that makes it difficult to read because my
newsreader is set to display in a window with only about enough
horizontal space for 80 odd characters. The result is that it re-wraps
your 100 character text lines so every other line is half as long as its
predecessor.

You could get around that by manually wrapping you text in the 60-80
character range and leaving the long lines for the code. Personally I do
the reverse and leave my newsreader wrapping posts at a relatively
narrow 72 characters but manually break my JavaScript so that I post
functional code (does not need to be unwrapped) within those margins.
Do you mean just hitting enter after June or
what is the proper way to break a line?

JavaScript (ECMA Script) is extremely tolerant of white space (including
line breaks) within its source code. There are in fact only a couple of
places where white space characters are not allowed. For example, a line
break may not be placed between a the - return - keyword and any
expression that is to be returned. The ECMA Script specification
describes this with the production for return:-

return [no-lineTerminator here] Expression (opt) ;

(the "opt" is subscript and refers to the semicolon being optional.)

So a statement such as:-

if((a)&&(a<b)&&(a>=c))d=a;

-may also be written as:-

if ( (a) && (a < b) && (a >= c) ) d = a;

-or-

if((a)&&
(a < b)&&
(a >= c)
)d = a;

-or-

if(
(a) && (a < b)&&(a >= c)
) d = a;

-or-

if (
(
a
) &&
(
a < b
) &&
(
a >= c
)
)
d = a;

-or (if you really wanted to write obscure code):-

if
(
(
a
)
&&
(
a
<
b
)
&&
(
a
c
)
)
d
=
a
;

-and the JavaScript interpreter would be able to sort it out and
determine that it was the same statement as the original.

One of the main reasons that JavaScript is so tolerant of white space is
to allow the structure of the source code (how the code is laid out in a
text editor) to convey additional meaning (usually related to structure
of the program) and maximise clarity for human readers. If you look at
the various examples above it should be clear that some are easier to
understand than others. The last, for example, would be close to
impossible to interpret and that would make source code structured in
that way extremely difficult to debug. The first (without any spaces) is
also not particularly clear.

The main source code structuring consideration that adds clarity is
block indenting (usually with tabs). A block is defined with curly
brackets - { - and - } - and represents a block statement (which may
contain zero or more other statements). It is normal to indent the
statements within a block by one tab character, though that tab is
usually set to 4 or less spaces width as the normal default 8 spaces
width is a bit too deep for most practical uses).

There are various common styles of block indenting, of which I prefer to
leave the opening - { - at the end of the control statement (on the same
line) and list the block contents as one statement per line, indented by
an additional tab with the closing - } - on a new line of its own one
tab out from the block contents so that it lines up vertically with the
start of the control statement. EG:-

function doSomething(oArea){
var nArea = oArea.nWidth * oArea.nHeitht;
var result = true;
if(!nArea){
removeRegion(oArea);
result = false;
}else if(nWidth < nHeight){
result = oArea.reShape(nArea);
}
return result;
}

The same function may also be commonly formatted:-

function doSomething(oArea)
{
var nArea = oArea.nWidth * oArea.nHeitht;
var result = true;
if(!nArea)
{
removeRegion(oArea);
result = false;
}
else if(nWidth < nHeight)
{
result = oArea.reShape(nArea);
}
return result;
}

-or-

function doSomething(oArea)
{
var nArea = oArea.nWidth * oArea.nHeitht;
var result = true;
if(!nArea)
{
removeRegion(oArea);
result = false;
}
else if(nWidth < nHeight)
{
result = oArea.reShape(nArea);
}
return result;
}

Though I very much dislike the latter.

In all cases the indenting servers to make the structure of the function
apparent in the structure of the source code. The important thing is to
pick an indenting style and stick to it (unless you find yourself
working for a company which has chosen its own house style for
indenting, in which case there are better arguments for all internal
code to be indented in that style).

Note that this is only relevant to development code, code downloaded
with a web page can be devoid of all the extra unnecessary white space
characters (and there are lots of programs that will automatically strip
them out) but during development (and when posting to news groups) code
should be as easy as possible to follow and understand.

However, Indenting with tab characters is not without it's problems when
posting to news groups, as at least some news software likes to strip
tabs out (or collapse them to single spaces). I always try to avoid that
problem by using the "convert tabs to spaces" feature on my text editor
prior to posting code. Also, It is usually best to read newsgroups on
which code if frequently posted in a fixed width font (else all the work
put in to extending clarity by formatting the source code becomes a bit
pointless).

The next consideration is how to handle long lines in news group posts.
Sometimes I find that just re-setting the width of the tab character to
2 (or 3) spaces will reduce the width of the code to within my required
72 character margins (prior to using the "convert tabs to spaces") and
no other adjustments are needed.

However, if a statement must be broken across several lines it should
not be indented at the same level as it's own start and it should not be
indented at the same level as its block contents (if any), but if block
indenting is at 4 space intervals then indenting a broken line at 1 to 3
characters should server to make it clear that it is indenting separate
from the general block structure of the code. EG:-

function otherWindowTest(obj){
if((document.compatMode)&&
(document.compatMode == 'CSS1Compat')&&
(document.documentElement)){ //<< broken statement
return document.documentElement;
}else if(document.body){
return document.body;
}else{
return obj;
}
};

Another alternative for formatting statements broken across lines is to
disregard the indenting on the left and line the code that belongs to
the broken statement up on the right hand side. EG:-

this.position = function(){
var sDsize;
if(--delay <= 0){
step();
if(((z+=fv) >= planeDepth)||
((dy+dm) > windowCenterY)||
((dx+dm) > windowCenterX)||
(v < 0)){ //right aligned broken statement
this.reset();
step();
}
div.top = (sy+(py*dy)-dm)+posMod;
div.left = (sx+(px*dx)-dm)+posMod;
divClip.height = (sDsize = (dm<<2)+posMod);
divClip.width = sDsize;
}
next.position();
};

To date I am yet to write a JavaScript that could not be formatted
reasonably to fit within the 72 character margins that I normally use
and both express it's block structure in it's format and be capable of
being cut directly form my posts and executed unaltered in a browser.

Richard.

(Your final code re-formatted to less than 72 character line lengths as
an example):-

function events() {
var today = new Date();
// [ ... ] == Array literal notation.
var dayarray = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
var montharray = [
"Jan","Feb","Mar",
"Apr","May","Jun",
"Jul","Aug","Sep",
"Oct","Nov","Dec"
];

document.write('<table border bgcolor="ffffff" cellpadding',
'="3"><tr><td><center><b>DATE</b><\/center>',
'<\/td><td><center><b>OPPONENT<\/b><\/center>',
'<\/td><\/tr>');
var ct = 1;
var hg = [
["2004/03/09 23:59:59","DES MOINES"],
["2004/03/19 23:59:59","LINCOLN"]
];

for (var i = (hg.length-1);i>=0;i--) {
var event = hg[1];
var date = new Date(hg[0]);
var year = 1900 + date.getYear()%1900 // < AD 3800
var cdate=dayarray[date.getDay()] +
", " +
montharray[date.getMonth()] +
" " +
date.getDate() +
" " +
year+" ";

if (ct <= 5) {
if (today.getTime() <= date.getTime()) {
ct++;
document.write('<tr><td valign=top>' +
cdate +
'<\/td><td> ' +
event +
'<\/td><\/tr>');
}
}
}
document.write('<\/table>');
}
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
Richard Cornford
It is normal to indent the
statements within a block by one tab character, though that tab is
usually set to 4 or less spaces width as the normal default 8 spaces
width is a bit too deep for most practical uses).

General agreement, except with your way of string alignment in the last
window-ful. I indent by a number of spaces representing the unclosed-
structure-depth at the beginning of the line[1], except sometimes, e.g.
if it's pleasing to get parts of lines "tabular".



However, if using the tab key, one needs to consider what may happen on
transfer of the code to another system, where the tab size may differ.

For a public medium, such as News, ISTM wise to convert the tab
characters to multiple spaces (I use 2; 1 is too few; 4 is quite
generous enough) before posting. It is likely that the tabs will be
expanded /en route/ anyway; but not necessarily to a convenient size.

For transfer to a coding colleague, however, preserve the tabs, and the
code should then be indented how he likes it.

I use multiple spaces; the space-bar is the one key that I can hit
reliably.


[1] I do the same in Pascal; it is much easier for the tool I wrote.
 
T

Treetop

Thanks for the detailed information. I am not a programmer
by trade, other than HTML, so it is nice to actually seeing
examples of what you are talking about. I have purchased a
couple of JavaScript books a while back, but they only
showed how to do math functions.

I noticed in the following line you put commas at the end of
each line. Is this needed for document.write commands? I
have also found out that it is recommended to put a
backslash before the close tag for HTML commands in
javascript.


document.write('<table border bgcolor="ffffff"
cellpadding',

'="3"><tr><td><center><b>DATE<\/b><\/center>',

'<\/td><td><center><b>OPPONENT<\/b><\/center>',
'<\/td><\/tr>');
 
R

Richard Cornford

... , except with your way of string alignment in the last
window-ful. I indent by a number of spaces representing the
unclosed-structure-depth at the beginning of the line[1],
except sometimes, e.g. if it's pleasing to get parts of lines
"tabular".
<snip>

If I understand what you are describing correctly, I would still like to
see statements that are broken across lines visibly distinct from the
block indenting, but I would not deny that it is just my opinion and not
objectively "correct". Just so long as the block structure is
consistently indented the rest is a relatively minor detail.

Richard.
 
R

Richard Cornford

Treetop said:
... I am not a programmer by trade, other
than HTML, so it is nice to actually seeing
examples of what you are talking about.

Don’t fool yourself, if you write JavaScript you become a programmer, by
trade or not. If you don't want to learn to be a programmer (preferably
a good programmer) put the JavaScript down and walk away now.
Cut-n-paste scripting is not an option for a professional page author,
it's understand how to script browsers or never even attempt to do so.
I have purchased a couple of JavaScript books a while
back, but they only showed how to do math functions.

Be cautions with JavaScript books, there are very few good ones [1] and
the majority are very out of date any way.
I noticed in the following line you put commas at the end of
each line. Is this needed for document.write commands?
<snip>

No, it is just one way of doing it. document.write can take many string
arguments (which would be comma separated (plus any white space)) and
will write them to the document in tern. So:-

document.write("a", "b", "c");

- will write "abc" into the document. As will:-

document.write("a"+"b"+"c");

- but that version uses the string concatenation operator (+) to join
the three strings together _before_ passing the result to the
document.write functions as only one argument.

Both multiple string concatenation and multiple document.write
statements can be relatively slow and inefficient. I prefer to only use
one document.write to output all of any constructed string in one go,
and recently I have been tending to avoid string concatenation by
building arrays of strings and then using the Array.prototype.join
method to convert that array into a single string in one operation.
Re-writing your function to use that approach produces:-

function events() {
var today = new Date().getTime(); //getTime here to avoid repeating
var dayarray = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
var montharray = [
"Jan","Feb","Mar",
"Apr","May","Jun",
"Jul","Aug","Sep",
"Oct","Nov","Dec"
];

var output = [
'<table border bgcolor="ffffff" cellpadding',
'="3"><tr><td><center><b>DATE<\/b><\/center>',
'<\/td><td><center><b>OPPONENT<\/b><\/center>',
'<\/td><\/tr>',
];

var hg = [
["2004/03/09 23:59:59","DES MOINES"],
["2004/03/19 23:59:59","LINCOLN"]
];

for (var i = hg.length, ct = 0, ol = output.length;i--; ) {
var date = new Date(hg[0]);
if (ct < 5) {
if (today <= date.getTime()) {
ct++;
output[ol++] = '<tr><td valign=top>';
output[ol++] = dayarray[date.getDay()];
output[ol++] = ", ";
output[ol++] = montharray[date.getMonth()];
output[ol++] = " ";
output[ol++] = date.getDate();
output[ol++] = " ";
output[ol++] = (1900 + date.getYear()%1900);
output[ol++] = " ";
output[ol++] = '<\/td><td> ';
output[ol++] = hg[1];
output[ol++] = '<\/td><\/tr>';
}
}else{
break; //end -for- loop as no more output will be generated
}
}
output[output.length] = '<\/table>';
document.write( output.join('') );
}

Richard.

[1] The comp.lang.javascript FAQ recommends just one JavaScript book:-

<URL: http://www.jibbering.com/faq/#FAQ3_1 >
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
Richard Cornford
Both multiple string concatenation and multiple document.write
statements can be relatively slow and inefficient. I prefer to only use
one document.write to output all of any constructed string in one go,
and recently I have been tending to avoid string concatenation by
building arrays of strings and then using the Array.prototype.join
method to convert that array into a single string in one operation.


That approach is, ISTM, suitable for the (near-)final production of
(near-)professional Web pages, where speed is important and correctness
is assured.[1]

But ISTM that, if implemented prematurely, it will only confuse both the
author and any helpers. Fragmented string output is more-or-less fast
enough, IMHO, on most computers for most pages. Though it is, of
course, good to know how to deal with the cases where it is not.

Re your bm1tsh$bjm$1$8300dec7 : Yes.


[1] In which case, all redundant spaces should be removed, identifiers
shortened and using all of A-Za-z0-9, etc.; there should be reliable
tools/methods for doing this.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,736
Latest member
AdolphBig6

Latest Threads

Top