How to Loop Through JavaScript Array?

0
You can loop any Array by using different types of looping statements in JavaScript, which I have previously posted. In this post you can loop through JavaScript Array. At first let you know basic concepts of Array ie. defining array, adding values to the array and accessing array elements. 

The Array object is used to store a set of values in a single variable name. You can define Array object with the new keyword.

The following line of code defines an Array object called  myArray.

var myArray=new Array()

You can also define the array size by passing an integer argument as follows.

var myArray=new Array(5)

You can add the values to an array as the following.

var myArray=new Array()
myArray[0]="value1"
myArray[1]="value2"
myArray[2]="value3"


You can also give values to the arrays while defining it as below.

var myArray=new Array("value1", "value2", "value3")

While accessing Arrays, you can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0. The following line accesses the first value of the array myArray.

document.write(myArray[0])


Loop Through JavaScript Array


You can loop any Array by using any of the following looping statements in JavaScript.

Using For loop


You can loop any Array by using For Loop as below.

var myArray=new Array()
myArray[0]="value1"
myArray[1]="value2"
myArray[2]="value3"

for(i=0; i<myArray.length;i++)
{
document.write(myArray[i])
}

Example:


<html>
<head></head>
<body>
<script type="text/javascript">
var mycars=new Array()
mycars[0]="Saab"
mycars[1]="Volvo"
mycars[2]="BMW"

for(i=0; i<mycars.length;i++)
{
document.write(mycars[i]+"<br/>")
}
</script>

Preview:


Using For .... In Statement


You can loop any Array by using For .... In Statement as below.

var myArray=new Array()
myArray[0]="value1"
myArray[1]="value2"
myArray[2]="value3"

for(x in myArray)
{
document.write(myArray[x])
}

Example:


<html>
<head></head>
<body>
<script type="text/javascript">
var mycars=new Array()
mycars[0]="Saab"
mycars[1]="Volvo"
mycars[2]="BMW"

for(x in mycars)
{
document.write(mycars[x]+"<br/>")
}
</script>
</body>
</html>

Preview:


You can also loop any Array by using other looping statements like while and Do ... while loops as the same methods given above.

Read Next:How to Concatenate, Join and Sort Array in JavaScript?

Related Search Terms

How to Loop using JavaScript?

0
Loops in JavaScript are used to execute the same block of code a specified number of times or while a specified condition is true.

In JavaScript there are two different kinds of loops which are for loop, which loops through a block of code a specified number of times and while loop, which loops through a block of code while a specified condition is true.

JavaScript For Loop


The for loop is used when you know in advance how many times the script should run.

Syntax:

for(var=startvalue; var<=endvalue;var=var+increment)
{
code to be executed
}

Example:

<html>
<head>
</head>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++){
document.write("The number is" +i)
document.write("<br/>")}
</script>
</body>
</html>

The above example defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs.

Preview:


JavaScript While Loop


The while loop is ued when you want the loop to execute and continue executing while the specified condition is true.

Syntax:

while (var<=endvalue)
{
code to be executed
}

Example:

<html>
<head></head>
<body>
<script type="text/javascript">
var i=0
while(i<=10)
{
document.write("The number is "+i)
document.write("<br/>")
i=i+1
}
</script>
</body>
</html>

The example above defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs.

Preview:


JavaScript do .... while Loop:


The do .... while loop is a variant of the while loop. This loop will always execute a block of code Once, and then it will repeat the loop as long as the specified condition is true. The lop alway be executed at least once, even if the condition is false, because the code is executed before the condition is tested.

Syntax:

do
{
code to be executed
}
while (var<=endvalue)

Example:

<html>
<head></head>
<body>
<script type="text/Javascript">
var i=0
do
{
document.write("The number is "+i)
document.write("<br/>")
i=i+i
}
while (i<0)
</script>
</body>
</html>

Preview:


JavaScrpt Break and Continue Statements


There are two special statements that can be used inside loops: break and continue.

Break

The break command will break the loop and continue executing the code that follows after the loop.

Example:

<html>
<head></head>
<body>
<script type="text/javascript">
var i=0
for(i=0;i<=10;i++)
{
if (i==3) {break}
document.write("The number is " +i)
document.write("<br/>")
}
</script>
</body>
</html>

Preview:


Continue

The continue command will break the current loop and continue with the next value.

Example:

<html>
<head></head>
<body>
<script type="text/javascript">
var i=0
for(i=0;i<=10;i++)
{
if (i==3) {continue}
document.write("The number is " +i)
document.write("<br/>")
}
</script>
</body>
</html>

Preview:


Read Next:How to Loop Through JavaScript Array?

Related Search Terms

How to Show Pop Up Boxes Using JavaScript?

0
Using JavaScript you can create three kinds of pop-up boxes, Alert box, Confirm box and prompt box.

Alert Box


An alert box is used if you want to make sure information comes through to the user. When an alert box pops up, the user will have to click on "OK" to processed.

Syntax:

alert("Alert Text")

Example:

<html>
<head>
<script type="text/javascript">
function display_alert()
{
alert("This is an alert box!")
}
</script>
</head>
<body>
<input type="button" onclick="display_alert()" value="Display alert box"/>
</body>
</html>

Preview:




 Conform box


A conform box is used if you want the user to verify or accept something. When a conform box pops up, the user will have to click either "OK" or "Cancel" to processed. If the user clicks "OK" the box returns true. If the user clicks "Cancel", the box returns false.

Syntax:

confirm{"Conform Text")

Example:

<html>
<head>
<script type="text/javascript">
function display_conform(){

r=confirm("Press a button");
if (r===true)
{
alert("You pressed OK!");
}
else
alert("You pressed Cancel");
}
</script>
<body>
<input type="button" onclick="display_conform()" value="Display a confirm box"/>
</body>
</html>

Preview:



 Prompt Box


A prompt box is used if you want the user to input a value before entering a page. When a prompt box pops up, the user will have to click "OK" or "Cancel" to processed entering in input value.
If the use clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.

Syntax:

prompt{"sometext", "defaultvalue"}

Example:

<html>
<head>
<script type="text/javascript">
function display_prompt(){
name=prompt("Please enter your name", "Your Name");
if ((name!=null) && name!=" ")
{
alert("Hello "+name+"! How are you today?");
}
}
</script>
</head>
<input type="button"onclick="display_prompt()" value="Display a prompt box"/>
</body>
</html>

Preview:


Related Search Terms

How to Write Conditional Statements in JavaScript?

0
The different types of conditional statements used in JavaScript for making different decisions are as follows.

If Statement


This statement is used to execute some code only if a specified condition is true.

Syntax:

if {condition}
{
code to be executed if condition is true
}

Example:

<script type="text/javascript">
var d=new Date()
var time=d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>")
}
</script>

This script writes "Good morning" greeting if the time is less than 10

If .... elese statement


This statement is used to execute some code only if the condition is true and another code if the condition is false.

Syntax:

if {condition}
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}

Example:

<script type="text/javascript">
var d=new Date()
var time=d.getHours()
if (time<10)
{
document.write("Good morning")
}
else
{
document.write("Good Day")
}
</script>

Preview:



If .... else If ..... else statement


This statement is used to select one of many blocks of code to be executed.

Syntax:

if {condition}
{
code to be executed if condition1 is true
}
else if {condition2}
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and condition2 are not true.
}

Example:

<script type="text/javascript">
var d=new Date()
var time=d.getHours()
if (time<10)
{
document.write("Good morning")
}
else if (time>=10 && time<16)
{
document.write("Good Day")
}
else
{
document.write("Hello World")
}
</script>

Preview:



Switch statement


This statement is used to select one of many blocks of code to be executed.

Syntax:

switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}

Example:

<script type="text/javascript">
var d=new Date();
theDay=d.getDay();
switch(theDay)
{
case 5:
document.write("Good Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I am looking forward to this weekend!");
}</script>

Preview:


How to Write JavaScript With HTML?

0
JavaScript is the most popular scripting language in the web to improve the design, validate forms, detect browsers, create cookies and many more client side functionalities and works in all major browsers, such as Internet Explorer, Mozilla Firefox, Google Chrome, Netscape, Opera and many more.

It is a lightweight programming language consisting of lines of executable computer code and usually embedded directly into HTML pages.

To write JavaScript with HTML page, you have to use the <script> tag along with the type attribute to define the scripting language. So the <script type="text/javascript"> and </script> tells where the javascript starts and end.


Different Ways to Write JavaScript with HTML


There are different ways to write JavaScript with HTML, which are as follows.

Scripts in the HEAD Section

When scripts are placed in head section, they needs to be executed when they are called, or when an event is triggered and it will ensure that the script is loaded before anyone uses it.

You can write <script> tag in the head section as follows.

<html>
<head>
<script type="text/javascript">
javascript codes are written here
</script>
</head>
<body>
</body>
</html>

Scripts in the BODY section

As in the head section, you can also place JavaScript codes in the body section using <script> tag and it will be executed when the page loads.

You can write <script> tag in the body section as follows.

<html>
<head>
</head>
<body>
<script type="text/javascript">
javascript codes are written here
</script>
</body>
</html>

Scripts in both the HEAD and BODY section

You can write <script> tag in both the head and body section as follows.

<html>
<head>
<script type="text/javascript"> 
javascript codes are written here
</script>
</head>
<body>
<script type="text/javascript">
javascript codes are written here
</script>
</body>
</html>


Scripts Using an External JavaScript File

If you needs to write same JavaScript code on several pages, you can write it on separate external page with a .js file extension and can link it to the HTML file.

You can link external JavaScript file to HTML file as follows.

<html>
<head>
<script src="javascript.js">
</script>
</head>
<body>
</body>
</html>

Read Next:

Related Search Terms

How to create Changeable Date and Time Using JavaScript?

0
You can create changeable Date and Time using JavaScript Date object. JavaScript Date object will automatically hold the current date and time as its initial value. You can manipulate it easily by using different methods in Date object. The different methods in Date object I am going to use to create changeable Date and Time are as follows.

  • Date():    Returns today's date and time.
  • getDate(): Returns the day of the month from a Date object from 1-31.
  • getDay():  Returns the day of the week from a Date object from 1-6
  • getMonth():Returns the month from a Date object from 0-11
  • getFullYear(): Returns the year, as a four digit number from Date object.
  • getHours():   Returns the hour of a Date object from 0-23.
  • getMinutes(): Returns the minutes of a Date object from 0-59
  • getSeconds(): Returns the seconds of a Date object from 0-59

Do do rest of the work you have to create a new Date() object and needs to use that value to get date, month, day name and time with hours, minutes and seconds. You can create variables for day, month and year as follows.

var now=new Date();
var today=now.getDate();
var month=now.getMonth();
var year=now.getFullYear();
var day=now.getDay();

You can create variables for hours, minutes and seconds as follows.

var now=new Date();
var hours=now.getHours();
var minutes=now.getMinutes();
var seconds=now.getSeconds();

After getting month and day in number format, you can change it into name of the month and day by using the arrays as follows.

var monthname=new Array(12)
monthname[0]="January ";
monthname[1]="February ";
monthname[2]="March ";
monthname[3]="April ";
monthname[4]="May ";
monthname[5]="June ";
monthname[6]="July ";
monthname[7]="August ";
monthname[8]="Septmber ";
monthname[9]="October ";
monthname[10]="November ";
monthname[11]="December ";

var dayname=new Array(7)
dayname[0]="Sunday ";
dayname[1]="Monday ";
dayname[2]="Tuesday ";
dayname[3]="Wednesday ";
dayname[4]="Thrusday ";
dayname[5]="Friday ";
dayname[6]="Saturday ";


Full HTML Code to Create Changeable Date


Here is a full HTML code to create changeable date, you can use these codes to display full date or you can customize to display in different format on your web page.

<html>
<body>
<script type="text/javascript">
function displayDate(){
var now=new Date();
var today=now.getDate();
var month=now.getMonth();

var monthname=new Array(12)
monthname[0]="January ";
monthname[1]="February ";
monthname[2]="March ";
monthname[3]="April ";
monthname[4]="May ";
monthname[5]="June ";
monthname[6]="July ";
monthname[7]="August ";
monthname[8]="Septmber ";
monthname[9]="October ";
monthname[10]="November ";
monthname[11]="December ";

var year=now.getFullYear();
var day=now.getDay();

var dayname=new Array(7)
dayname[0]="Sunday ";
dayname[1]="Monday ";
dayname[2]="Tuesday ";
dayname[3]="Wednesday ";
dayname[4]="Thrusday ";
dayname[5]="Friday ";
dayname[6]="Saturday ";

document.write(monthname[month]+today+ ", "+year+ " "+dayname[day]);
}
window.onload=displayDate();
</script>
</body>
</html>

Preview of Date Displayed:


Full HTML Code to Create Changable Time


Here is a full HTML code to create changeable time, you can use these codes to display full time or you can customize to display in different format on your web page. You can use these codes to create digital clock using JavaScript, which I have already posted in my previous post.

<html>
<head></head>
<body>
<script type="text/javascript">
function startTime()
{
var today=new Date()
var h=today.getHours()
var m=today.getMinutes()
var s=today.getSeconds()
var ap="AM";

//to add AM or PM after time

if(h>11) ap="PM";
if(h>12) h=h-12;
if(h==0) h=12;

//to add a zero in front of numbers<10

m=checkTime(m)
s=checkTime(s)

document.getElementById('clock').innerHTML=h+":"+m+":"+s+" "+ap
t=setTimeout('startTime()', 500)
}

function checkTime(i)
{
if (i<10)
{ i="0" + i}
return i
}

window.onload=startTime;

</script>

<div id="clock"></div>
</body>
</html>

Preview of Time Displayed:




Related Posts:

How to Validate a HTML Form Using JavaScript?

0
In the previous post, I have described about "How to create a simple form using HTML" step by step with describing what is a form and what elements are used to create HTML form along with complete HTML code for a form. In this post I am going to describe about to Validate a this HTML Form Using JavaScript.

You can validate a HTML Form Using JavaScript for the following circumstances.

  • Whether or not the user left required fields empty
  • Whether or not the user entered a valid e-mail address
  • Whether or not the user entered a valid date
  • Whether or not the user entered text in numeric field or entered number in text field

Here in this post I am going to describe you, "How to Validate Required Fields using JavaScript.

Validating Required Field using JavaScript


This JavaScript Function below checks if a required field has been left empty. If the required field is blank, an alert box alerts a message and the function returns false. If the value is entered the function returns true.

function validate_required(field, alerttxt)
{
with(field)
{
if (value===null||value==="")
{alert(alerttxt); return false;}
else {return true;}
}
}

Complete JavaScript Code with HTML for Validating Required Field


Here are the complete JavaScript codes along with complete HTML codes uses with the JavaScript Functions given below.

<html>
<head><title>Subscription Form</title>
<script type="text/javascript">
function validate_required(field, alerttxt)
{
with(field)
{
if (value===null||value==="")
{alert(alerttxt); return false;}
else {return true;}
}
}

function validate_form(thisform)
{
with(thisform)
{
if (validate_required(fname, "First name must be filled out!")===false)
{fname.foucus(); return false;}
if (validate_required(lname, "Last name must be filled out!")===false)
{lname.foucus(); return false;}
if (validate_required(password, "Password must be filled out!")===false)
{password.foucus(); return false;}
if (validate_required(rpassword, "Retype Password must be filled out!")===false)
{rpassword.foucus(); return false;}
}
}
</script>
</head>
<body>
<FORM METHOD='GET' ONSUBMIT="return validate_form(this);" ACTION="http://www.siteforinfotech.com/p/about-us.html">
<DIV>First Name:<INPUT TYPE='text' NAME='fname' VALUE='Enter First Name' SIZE=30 MAXLENGTH=25></DIV><br/>
<DIV>Last Name:<INPUT TYPE='text' NAME='lname' VALUE='Enter Last Name' SIZE=30 MAXLENGTH=25></DIV><br/>
<DIV>Password:<INPUT TYPE='password' NAME='password' SIZE=30 MAXLENGTH=25></DIV><br/>
<DIV>Retype Password:<INPUT TYPE='password' NAME='rpassword' SIZE=30 MAXLENGTH=25></DIV><br/>
<DIV>Email:<INPUT TYPE='text' NAME='email' VALUE='Enter Your Email' SIZE=30 MAXLENGTH=25></DIV><br/>
<br/>
<INPUT TYPE='submit' VALUE='Submit'><INPUT TYPE='reset' VALUE='Reset'>
</FORM>
</body>
</html>


Preview of the above HTML Code



First Name:

Last Name:

Password:

Retype Password:

Email:



يتم التشغيل بواسطة Blogger.