More on Arrays and Loops
<font color="red" size=4>WebTV JS "Bug" - Reload Page (cmd-r)</font>

JS is based on arrays. All information in JS objects is stored in linear arrays. The arrays so far discussed are those that may be used in writing a page, but the construct is no different from that which is built into a JS browser. Before developing the array concept as applied to the Document Object Model (DOM), though, it is appropriate to complete development of arrays as applied when composing a page and some additional aspects of for loops.

Creating Arrays  Throughout the descriptions of programming using JS arrays, their elements have been presented in the same sense as independent variables, i.e., each element in an array was defined in an independent manner. It is not necessary to do so, though, for the order to each element in an array is already implied. That is, instead of creating a new array in this manner:

name=new Array()
name[0]="Smith"; name[1]="Jones"; name[2]="Doe"


it is just as valid, and more convenient, to do it this way instead:

name=new Array("Smith", "Jones", "Doe")


Each element is separated by a comma and is indexed starting with 0, and each is used just as with the longer definition for them. The number of elements in an array do not even have to be counted when the array is created since, in a manner similar to finding the length of a string variable, the number of elements, noelem, in an array is obtained from:

noelem=name.length


There is no table array storage in JS. Every array is a linear array. To create tables from a linear array is a matter of using appropriately nested for loops, which is shown later.

A simple illustration of an array application is shown below. First the array is defined and the number of elements in it determined. In this case there is an array for image URLs and one for the caption A function is made which will be accessed on every click of the button. Prior to creating the function the count for how many times the function is accessed is initialized. The last statement in the function tests whether the number of times the function is used is more than the number of array elements. If so the count is re-initialized. The count is used as the index for an array element, modified as may be necessary. Note that only the first image is placed before the form, and must be given a name. All others will appear in the same place. There are as many captions as there are images, and these are made to display in the form window.

<script>
imag=new Array("URL1","URL2","URL3","URL4")
capt=new Array("Note1","Note2","Note3", "Note4");
num=imag.length;ct=0;ct=0;
   function strt()
     {ct=ct+1;pic=imag[ct-1];
     document.img1.src=pic;
     window.document.display.caption.value=capt[ct-1];
     if(ct ==nimag){ct=0;}}
</script>

<form name="display">
<img src="URL1" name="img1"><input type="text" name="caption" readonly="readonly">
<input type="button" value="Go" onClick="strt()">
</form>






Interrupting Loops  In seeking to match an item in an array with an input value the loop will keep on going even after a match is found. This is tolerable if the last element in an array is the matching one. However, if the match is found with the first element or even midway in the array, there is no reason to continue the loop, especially if there are many hundreds of elements. For this there is a break statement that can be used:

for(i=0; i < noelem; i++)
{if(i=itemWanted){break};}


Once a break occurs, program flow passes immediately to the next statement.

A for loop can be sustained, though, and items skipped over using a continue statement. Here is a simple timer using the continue statement, for this example in a nested for loop

for(i=0; i < noelem; i++)
{
   for(j=0; j < 10000; j++)
   {continue}
}


In this the first loop sequences a count. The second does nothing but continue a long second count, where the maximum is set at a large enough number to give the desired delay between counts of the first loop.

This is the delay effect just using a for loop with a continue. Put a number greater than 10000 in below and increase in increments of 10000 to see the effect.




Commentaries  As a programming language, JS requires a shift in perspective from what one is accustomed to with HTML. It is what is desired as being accomplished by the programming and not the "look" of a page that is the more important. In trying to meet what is desired each JS statement is organized in a sequential manner so as to provide whatever may be needed for the step or steps following. In specifying what each step is to do commentaries can be made to describe what is being done, which both helps in giving the logic to the steps taken and recording what was done to aid in any later modification. It may not be remembered a month or two from now what was done this week.

Another great distinction is that punctuation, spacing, and attention to syntax is even more important than with HTML. The program just will not work otherwise. Indexing, as with arrays, also has to be modified using a little arithmetic at times so as to maintain a proper count or access variables appropriately. Too, all textual inputs are strings and text outputs are usually strings. So inputs at times must be converted to numeric for their functioning properly. And results must be made into a concatinated string many times to present them. A commentary helps in showing when this may be the case.

In HTML the beginning of comment is <!-- and the end is --->. What is in between is seen when coding but is not executed when run. JS has its own commentaries, for anything in HTML within a scripted routine is ignored. One of these is / /, which must have a space between. The usual HTML commentary tags may also be included. A comment may be entered by placing at the beginning of a statement line

<!--/ / JS Statement    - Comment here --->


The statement and comment should be no more than a single line, as this form for a comment will mask that line whether JS is active or not. An alternative placement of the / / applies when a browser does not support JS and when script will be tried to be read as HTML is shown below:

<script>
<!-- HIDE THE SCRIPT FROM OTHER BROWSERS
JavaScript program
// STOP HIDING FROM OTHER BROWSERS -->
</script>


The problem is that whether this will function in the manner intended can vary with level of JS and browser. For example, writing the latter part of this code with a space, / /-->, inactivates a JS program in WebTV's Page Builder, while without a space, //-->, the JS program will function (With thanks to richardo for pointing this out).

A far more useful commentary code places /* at the beginning and */ at the end, in the same manner as is done with HTML comment tags. Many lines can be included between them. They are not only suitable for making comments, but they can also be used as a "de-bugging" tool. Bracket what is thought to hinder operation of a JS routine, and if the routine runs then the programming problem is localized. Remember to remove them after having made any correction. The example which follows has such a commentary within the program. It is a routine which takes an input sentence and converts every character to its alt-equivalent. Where there is no alt-equivalent an alt-8 (•) has been used. No single or double quotes should be used as these would have truncated the stored strings. Spaces should be replaced by an underline, as many practice. Nothing beyond what has been described previously is in the routine. For those interested, the results can be cut, copied, and pasted.

<script>
function trans()
{

/* Get Sentence Input */

start=window.document.sent.text.value;

/* Make Upper Case as is Stored String */

start=start.toUpperCase(this);

/* No. Characters in Input */

nchar=start.length;

/* Stored Strings */

/ / Normal Alphabet;
var abc="QWERTY...";
/ / Alt-Alphabet;
var alt="朕®þ¥...";

/* Length of Each Stored String */

abcln=abc.length;altln=alt.length;

/* Initialize Output String(s) */

var eng=" ";var sans=" ";

/*Scan For Each Character Input */

for(i=1; i <= nchar; i++)
{
chct=start.substring(i-1,i);

/* Check against Alphabet */

for(j=1; j <= abcln; j++)
{
alchr=abc.substring(j-1,j);
if(alchr == chct)
{sans=sans+alt.substring(j-1,j);break}
}
}

/* Output Result */

window.document.sent.lang.value=sans}
</script>

<form name="sent"><input type="text" name="text"><input type="button value=Tell Me" onClick="trans()">
<textarea name="lang" cols=20 rows=7 nohighlight>
</textarea>
<input type="reset" value="Clear">






JS Test-Bed 1 - - JS Test-Bed 2



<< PreviousNext >>