Site hosted by Angelfire.com: Build your free website today!
 
MyersDaily Directories
New ! -> Practical List Encryption
What's Up | Contents | Bottom of Page
[Pages][Home]
Run Scripts

A "for" loop provides an excellent method for reducing script size by compacting code and allowing for direct processing of lists, etc.

The general syntax of a for loop is as follows:

for (var VARIABLE = INITIAL_VALUE; CONDITION; MODIFY) {
	// EXECUTE STATEMENTS
}

Quick Tip: Note the use of the var keyword to initialize the variable. Although its use is optional by the same definition as that of a normal variable, make it a habit to use it!

The reason why this method is so excellent is that it allows for you to use the value of the variable, typically "i" inside of the body of the loop, and also gives a very compact format more efficient than using a while loop for the same purpose.

Suppose you had an array of values, and you wanted to change all the values which equaled 5 or '5' to 10. (This is a very basic use.)

var array_of_values = [1, 7, 5, 4, '5'];
for (var i = 0; i<array_of_values.length; i++) {
	if (array_of_values[i] == 5) {
		array_of_values[i] = 10;
	}
}

When this script has been run, the modified version of "array_of_values" now has the following.

array_of_values = [1, 7, 10, 4, 10];

This example is not really very meaningful. A more typical use might be to change any non-numeric value to 0. By changing the condition in the if statement and its assignment we can accomplish this.

if (isNaN(array_of_values[i])) {
	array_of_values[i] = 0;
}

As you can see from both of these examples, the for loop has shortened considerably the trouble it took to perform those tasks.

 
Enter keywords...  
Amazon.com logo Featured! | Send to a friend!
Home | Top | Feedback | Site Index | Best Photo
“MyersDaily” created by Joseph K. Myers 1999-2000. Free hosting by Angelfire!!
Note: This site's URL is: https://www.angelfire.com/yt/jmyers   Site Updated On: October 6, 2000
Terms-of-Service