http://www.cev.washington.edu/lc/CLWEBCLB/jst/js_looping.html
Looping
Very often when you write code, you want the same block of code to run a number of times. You can use looping statements in your code to do this.
In JavaScript we have the following looping statements:
- while - loops through a block of code while a condition is true
- do...while - loops through a block of code once, and then repeats the loop while a condition is true
- for - run statements a specified number of times
while
The while statement will execute a block of code while a condition is true..
while (condition) { code to be executed } |
do...while
The do...while statement will execute a block of code once, and then it will repeat the loop while a condition is true
do { code to be executed } while (condition) |
for
The for statement will execute a block of code a specified number of times
for (initialization; condition; increment) { code to be executed } |
Examples
For loop
How to write a For loop. Use a For loop to run the same block of code a specified number of times
<html> <body> <script type="text/javascript"> for (i=0; i<=5; i++) { document.write("<b>The number is " + i + "</b>") document.write("<br>") } </script> <p>Explanation: <p>The for loop sets <b>i</b> equal to 0. <p>As long as <b>i</b> is less than or equal to 5, the loop will continue to run. <p><b>i</b> will increase by 1 each time the loop runs. </body> </html> |
Looping through HTML headers
How to use the For loop to write the HTML headers.
<html> <body> <script type="text/javascript"> for (i=0; i<=6; i++) { document.write("<h" + i + ">This is header " + i) document.write("</h" + i + ">") } </script> <p>Explanation: <p>The for loop sets <b>i</b> equal to 0. <p>As long as <b>i</b> is less than or equal to 5, the loop will continue to run. <p><b>i</b> will increase by 1 each time the loop runs. </body> </html> |
While loop
How to write a While loop. Use a While loop to run the same block of code while or until a condition is true
<html> <body> <script type="text/javascript"> i=0 while (i<=5) { document.write("<b>The number is " + i + "</b>") document.write("<br>") i++ } </script> <p>Explanation: <p>The for loop sets <b>i</b> equal to 0. <p>As long as <b>i</b> is less than or equal to 5, the loop will continue to run. <p><b>i</b> will increase by 1 each time the loop runs. </body> </html> |
Do while loop
How to write a Do While loop. Use a Do While loop to run the same block of code while or until a condition is true. This loop will always be executed once, even if the condition is false, because the statements are executed before the condition is tested
<html> <body> <script type="text/javascript"> i=0 do { document.write("<b>The number is " + i + "</b>") document.write("<br>") i++ } while (i<=5) </script> <p>Explanation: <p>The for loop sets <b>i</b> equal to 0. <p>As long as <b>i</b> is less than or equal to 5, the loop will continue to run. <p><b>i</b> will increase by 1 each time the loop runs. </body> </html> |
JavaScript String Object
The Most Common Methods
NN: Netscape, IE: Internet Explorer, ECMA: Web Standard
Methods | Explanation | NN | IE | ECMA |
---|---|---|---|---|
length | Returns the number of characters in a string | 2.0 | 3.0 | 1.0 |
indexOf() | Returns the index of the first time the specified character occurs, or -1 if it never occurs, so with that index you can determine if the string contains the specified character. | 2.0 | 3.0 | |
lastIndexOf() | Same as indexOf, only it starts from the right and moves left. | 2.0 | 4.0 | |
match() | Behaves similar to indexOf and lastIndexOf, but the match method returns the specified characters, or "null", instead of a numeric value. | 4.0 | 4.0 | |
substr() | Returns the characters you specified: (14,7) returns 7 characters, from the 14th character. | 4.0 | 4.0 | |
substring() | Returns the characters you specified: (7,14) returns all characters between the 7th and the 14th. | 2.0 | 3.0 | 1.0 |
toLowerCase() | Converts a string to lower case | 2.0 | 3.0 | 1.0 |
toUpperCase() | Converts a string to upper case | 2.0 | 3.0 | 1.0 |
Examples
The length method
The length method returns the number of characters in a string.<html> <body> <script type="text/javascript"> var str="Web Enabling Tools is Cool!" document.write("<p>" + str + "</p>") document.write("str.length") </script> </body> </html> |
The indexOf() method
Test if a string contains a specified character. Returns an integer if it does and -1 if it does not. Use this method in a form validation.<html> <body> <script type="text/javascript"> var str="Web Enabling Tools is Cool!" var pos=str.IndexOf("Enabling") if (pos>=0) { document.write("School found at position: ") document.write(pos + "<br>") } else { document.write("Enabling not found!") } <p>This example tests if a string contains a specified word. If the word is found it returns the position of the first character of the word in the original string. Note: The first position in the string is 0! </script> </body> </html> |
The match() method
Works similar to the indexOf method, only this method returns the characters you specified, "null" if the string does not contain the specified characters.<html> <body> <script type="text/javascript"> var str="Web Enabling Tools is cool!" document.write(str.match("cool")) </script> <p>This example tests if a string contains a specified word. If the word is found it returns the word! </body> </html> |
The substr() method
Returns a specified part of a string. If you specify (3,6) the returned result string will be from the third character and 6 long. (Note that since the first character is 0, the second is 1 etc, the result will be from the second character and 6 long).<html> <body> <script type="text/javascript"> var str="W3Schools is great!" document.write(str.substr(2,6)) document.write("<br><br>") document.write(str.substring(2,6)) </script> <p>The substr() method returns a specified part of a string. If you specify (2,6) the returned string will be from the second character (start at 0) and 6 long. <p>The substring() method also returns a specified part of a string. If you specify (2,6) it returns all characters from the second character (start at 0) and up to, but not including, the sixth character. </body> </html> |
The substring() method
Returns a specified part of a string. (3,6) returns the characters from the third to the 6th.<html> <body> <script type="text/javascript"> var str="W3Schools is great!" document.write(str.substring(3,6)) </script> <p>This example returns all the characters from the third character up to but not including the 6th character. (Note that since the first character is 0, the second is 1 etc, the result will be from the fourth character including the 6th character). </body> </html> |
The toLowerCase() and toUpperCase() methods
Converts a string to lower case and upper case respectively.<html> <body> <script type="text/javascript"> var str=("Hello JavaScripters!") document.write(str.toLowerCase()) document.write("<br>") document.write(str.toUpperCase()) </script> </body> </html> |
JavaScript Array Object
The Array object
An Array object is used to store a set of values in a single variable name. Each value is an element of the array and has an associated index number.
You can refer to a particular element in the array by using the name of the array and the index number. The index number starts at zero.
You create an instance of the Array object with the "new" keyword.
var family_names=new Array(5) |
The expected number of elements goes inside the parentheses, in this case 5.
You assign data to each of the elements in the array like this:
family_names[0]="Tove" family_names[1]="Jani" family_names[2]="Ståle" family_names[3]="Hege" family_names[4]="Kai" |
And the data can be retrieved from any element by using the index of the particular array element you want. Like this:
mother=family_names[0] father=family_names[1] |
The Most Common Methods
Methods | Explanation | NN | IE | ECMA |
---|---|---|---|---|
length | Returns the number of elements in an array. This property is assigned a value when an array is created | 3.0 | 4.0 | 1.0 |
reverse() | Returns the array reversed | 3.0 | 4.0 | 1.0 |
slice() | Returns a specified part of the array | 4.0 | 4.0 | |
sort() | Returns a sorted array | 3.0 | 4.0 | 1.0 |
Examples
Array
Arrays are used to store a series of related data items. This example demonstrates how you can make an array that stores names.<html> <body> <script type="text/javascript"> var famname = new Array(6) famname[0] = "Jan Egil" famname[1] = "Tove" famname[2] = "Hege" famname[3] = "Stale" famname[4] = "Kai Jim" famname[5] = "Borge" for (i=0; i<6; i++) { document.write(famname[i] + "<br>") } </script> </body> </html> |
Array 2
This is another way of making an array that gives the same result as the one above. Note that the length method is used to find out how many elements the array contains.<html> <body> <script type="text/javascript"> var famname = new Array("Jan Egil","Tove","Hege","Stale","Kai Jim","Borge")for (i=0; i document.write(famname[i] + "<br>") } </script> </body> </html> |
JavaScript Date ObjectThe Date objectThe Date object is used to work with dates and times.You create an instance of the Date object with the "new" keyword. To store the current date in a variable called "my_date":
The Most Common MethodsNN: Netscape, IE: Internet Explorer, ECMA: Web Standard
ExamplesDateReturns today's date including date, month, and year. Note that the getMonth method returns 0 in January, 1 in February etc. So add 1 to the getMonth method to display the correct date.
TimeReturns the current local time including hour, minutes, and seconds. To return the GMT time use getUTCHours, getUTCMinutes etc.
Set dateYou can also set the date or time into the date object, with the setDate, setHour etc. Note that in this example, only the FullYear is set.
UTC timeThe getUTCDate method returns the Universal Coordinated Time which is the time set by the World Time Standard.
Display weekdayA simple script that allows you to write the name of the current day instead of the number. Note that the array object is used to store the names, and that Sunday=0, Monday=1 etc.
Display full dateHow to write a complete date with the name of the day and the name of the month.
Display timeHow to display the time on your pages. Note that this script is similar to the Time example above, only this script writes the time in an input field. And it continues writing the time one time per second.
JavaScript Math ObjectExamplesThe Math object
The built-in Math object includes mathematical constants and functions. You do not need to create the Math object before using it.
To store a random number between 0 and 1 in a variable called "r_number":
To store the rounded number of 8.6 in a variable called "r_number":
The Most Common Methods
NN: Netscape, IE: Internet Explorer, ECMA: Web Standard
RoundHow to round a specified number to the nearest whole number
Random numberThe random method returns a random number between 0 and 1
Random number from 0-10How to write a random number from 0 to 10, using the round and the random method.
Max numberHow to test which of two numbers, has the highest value.
Min numberHow to test which of two numbers, has the lowest value.
|
No comments:
Post a Comment