Wednesday, April 25, 2018

JavaScript Looping and Objects

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
MethodsExplanationNNIEECMA
lengthReturns the number of characters in a string2.03.01.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.03.0
lastIndexOf()Same as indexOf, only it starts from the right and moves left.2.04.0
match()Behaves similar to indexOf and lastIndexOf, but the match method returns the specified characters, or "null", instead of a numeric value.4.04.0
substr()Returns the characters you specified: (14,7) returns 7 characters, from the 14th character.4.04.0
substring()Returns the characters you specified: (7,14) returns all characters between the 7th and the 14th.2.03.01.0
toLowerCase()Converts a string to lower case2.03.01.0
toUpperCase()Converts a string to upper case2.03.01.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

MethodsExplanationNNIEECMA
lengthReturns the number of elements in an array. This property is assigned a value when an array is created3.04.01.0
reverse()Returns the array reversed 3.04.01.0
slice()Returns a specified part of the array4.04.0
sort()Returns a sorted array3.04.01.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 Object


The Date object

The 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":
var my_date=new Date()
After creating an instance of the Date object, you can access all the methods of the object from the "my_date" variable. If, for example, you want to return the date (from 1-31) of a Date object, you should write the following:
my_date.getDate()
You can also write a date inside the parentheses of the Date() object, like this:
new Date("Month dd, yyyy hh:mm:ss")
new Date("Month dd, yyyy")
new Date(yy,mm,dd,hh,mm,ss)
new Date(yy,mm,dd)
new Date(milliseconds)
Here is how you can create a Date object for each of the ways above:
var my_date=new Date("October 12, 1988 13:14:00")
var my_date=new Date("October 12, 1988")
var my_date=new Date(88,09,12,13,14,00)
var my_date=new Date(88,09,12)
var my_date=new Date(500)


The Most Common Methods

NN: Netscape, IE: Internet Explorer, ECMA: Web Standard
MethodsExplanationNNIEECMA
Date()Returns a Date object2.03.01.0
getDate()Returns the date of a Date object (from 1-31)2.03.01.0
getDay()Returns the day of a Date object (from 0-6. 0=Sunday, 1=Monday, etc.)2.03.01.0
getMonth()Returns the month of a Date object (from 0-11. 0=January, 1=February, etc.)2.03.01.0
getFullYear()Returns the year of the Date object (four digits)4.04.01.0
getHours()Returns the hour of the Date object (from 0-23)2.03.01.0
getMinutes()Returns the minute of the Date object (from 0-59)2.03.01.0
getSeconds()Returns the second of the Date object (from 0-59)2.03.01.0

Examples


Date

Returns 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.
<html>
<body>
<script type="text/javascript">
var d = new Date()
document.write(d.getDate())
document.write(".")
document.write(d.getMonth() + 1)
document.write(".")
document.write(d.getFullYear())
</script>
</body>
</html>

Time

Returns the current local time including hour, minutes, and seconds. To return the GMT time use getUTCHours, getUTCMinutes etc.
<html>
<body>
<script type="text/javascript">
var d = new Date()
document.write(d.getHours())
document.write(".")
document.write(d.getMinutes() + 1)
document.write(".")
document.write(d.getSeconds())
</script>
</body>
</html>

Set date

You 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.
<html>
<body>
<script type="text/javascript">
var d = new Date()
d.setFullYear("1990")
document.write(".")
</script>
</body>
</html>

UTC time

The getUTCDate method returns the Universal Coordinated Time which is the time set by the World Time Standard.
<html>
<body>
<script type="text/javascript">
var d = new Date()
document.write(d.getUTCHours())
document.write(".")
document.write(d.getUTCMinutes() + 1)
document.write(".")
document.write(d.getUTCSeconds())
</script>
</body>
</html>

Display weekday

A 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.
<html>
<body>
<script type="text/javascript">
var d = new Date()
var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
document.write("Today is " + weekday[d.getDay()])
</script>
</body>
</html>

Display full date

How to write a complete date with the name of the day and the name of the month.
<html>
<body>
<script type="text/javascript">
var d = new Date()
var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
document.write(weekday[d.getDay()] + " ")
document.write(d.getDate() + ". ")
document.write(monthname[d.getMonth()] + " ")
document.write(d.getFullYear())
</script>
</body>
</html>

Display time

How 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.
<html>
<body>
<script type="text/javascript">
var timer = nullfunction stop()
{
clearTimeout(timer)
}
function start()
{
var time = new Date()
var hours = time.getHours()
minutes=((minutes < 10) ? "0" : "") + minutes
var seconds = time.getSeconds()
seconds=((seconds < 10) ? "0" : "") + seconds
var clock = hours + ":" + minutes + ":" + seconds
document.forms[0].display.value = clock
timer = setTimeout("start()",1000)
}
</script>
</body>
</html>


JavaScript Math Object

Examples

The 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":
r_number=Math.random()
To store the rounded number of 8.6 in a variable called "r_number":
r_number=Math.round(8.6)


The Most Common Methods

NN: Netscape, IE: Internet Explorer, ECMA: Web Standard
MethodsExplanationNN IEECMA
max(x,y)Returns the number with the highest value of x and y2.03.01.0
min(x,y)Returns the number with the lowest value of x and y2.03.01.0
random()Returns a random number between 0 and 12.03.01.0
round(x)Rounds x to the nearest integer2.03.01.0

Round

How to round a specified number to the nearest whole number
<html>
<body>
<script type="text/javascript">
document.write(Math.round(7.25))
</script>
</body>
</html>

Random number

The random method returns a random number between 0 and 1
<html>
<body>
<script type="text/javascript">
document.write(Math.random())
</script>
</body>
</html>

Random number from 0-10

How to write a random number from 0 to 10, using the round and the random method.
<html>
<body>
<script type="text/javascript">
no=Math.random()*10
document.write(Math.floor(no))
</script>
</body>
</html>

Max number

How to test which of two numbers, has the highest value.
<html>
<body>
<script type="text/javascript">
document.write(Math.max(2,4))
</script>
</body>
</html>

Min number

How to test which of two numbers, has the lowest value.
<html>
<body>
<script type="text/javascript">
document.write(Math.min(2,4))
</script>
</body>
</html>


No comments:

Computer Terms

The termination of the process due to a program or system fault      -      Abend(abnormal ending) To terminate a process before completion....