Saturday 2 June 2012

Simple Example of Array in Javascript


Introduction:

This is the small article but very important to return the day of the week. To find the day of week JavaScript provides the Date object. Date object contain the many methods. getDay() method is one of them.

getDay(): It returns the day of the week.

In the following example we will use an array to hold the days of week.

Example 1: 

<html>
  <head>
    <title>Day of Week</title>
  </head>
  <body>
    <script type="text/javascript">
    var d=new Date()
    var weekday=new Array(7)
    weekday[0]="Sunday"
    weekday[1]="Monday"
    weekday[2]="Tuesday"
    weekday[3]="Wednesday"
    weekday[4]="Thursday"
    weekday[5]="Friday"
    weekday[6]="Saturday"
    document.write("Today it is " + weekday[d.getDay()])
    </script>
  </body>
</html>

Document.write is a java script command. It is used for writing the output to a page.

Output:


Figure 1: This figure shows the name of day.

Another way to find the day and date simultaneously in JavaScript:

Example 2:

<html>
  <head>
    <title>Day of Week</title> 
  </head>
  <body bgcolor=olive><font color="navy">
    <script type="text/javascript">
    document.write(Date())
    </script></font>
  </body>
</html>

In this example we are using Date object directly so the output will be as following:
  

Figure 2: This figure show the day and date.

No comments:

Post a Comment