Topic 2 CSS

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

 Client Side Scripting Language 2-1 Array, Function and String



2. Array, Function and String (14 M)




2.1 Array
 Definition of Arrays : Arrays is a collection of similar type of elements which can be referred by a
common name.
 Any element in an array is referred by an array name followed by “[“ followed by position of the
element followed by ].
 The particular position of element in an array is called array index or subscript.

For example –

Fig. 2.1.1 Arrays

 Normally the first element in an array is stored at 0th location, however we can start storing the
element from any position.

2.1.1 Declaring an Array


 In JavaScript the array can be created using Array object.
 Suppose, we want to create an array of 10 elements then we can write,
var ar = new Array(10);
 Using new operator we can allocate the memory dynamically for the arrays.
 In the brackets the size of an array is mentioned and the var ar denotes the name of the array. Thus by
the above sentence an array ar will be created in which we can store 10 elements at the most.
Sometimes the above statement can be written like this
var ar;
ar=new Array(10);

2.1.2 Initializing an Array


 Initialization is the process of assigning a value when either a variable or array is declared. For
example
int count=10//variable initialization

TM
Technical Publications (2
- An up thrust for knowledge
- 1)
Client Side Scripting Language 2-2 Array, Function and String

 While initializing an array -


1) Declare name of the array
2) Make use of the keyword new
3) Each value within an array as an ‘array element’ must be separated by comma.
 For example –

Fig. 2.1.2

2.1.3 Defining an Array Elements


 The elements in the array are stored from index 0.
 For example – elements in array 10,20,30,40,50 are stored as follows –

Fig. 2.1.3

 Following is a simple JavaScript that illustrates the initialization of array by defining the array
elements.

JavaScript Document
<!DOCTYPE html>
<html>
<head>
<title>Array Demo</title>
</head>
<body>
<strong>
<script type="text/javascript">
a=new Array(5);//creation of array
for(i=0;i<5;i++)
{
a[i]=i;
document.write(a[i]+"<br>");//displaying array
}
document.write("Another way of initialization"+"<br>");
b=new Array(11,22,33,44,55);//creation of array
for(i=0;i<5;i++)
{
document.write(b[i]+"<br>");//displaying array
}
document.write("Yet another way of initialization"+"<br>");
Client Side Scripting Language 2-3 Array, Function and String

var c=[100,200,300,400,500];//creation of array


for(i=0;i<5;i++)
{
document.write(c[i]+"<br>");//displaying array
}
</script>
</strong>
</body>
</html>
Script Explanation : In above JavaScript, as you can notice that, an array can be initialized in three
different ways which is shown by boldface. Hence an output of above script will be
Output

Ex. 2.1.1 : Write a JavaScript to define the array elements and to find the length of array.
Sol. : <!DOCTYPE html>
<html>
<head>
<title>Array Demo</title>
</head>
<body>
<script type="text/javascript">
a=new Array(11,22,33,44,55);//creation of array
var len=a.length
Client Side Scripting Language 2-4 Array, Function and String

document.write("The length of array is: "+len)


</script>
</body>
</html>
Output

Script Explanation : In above JavaScript, We have used length property to calculate length of the array.
This actually gives total number of elements in the array.

2.1.4 Looping an Array


 Looping an array means visiting each element present in the array.
 Following JavaScript illustrates how to loop or iterate through the elements of array –

JavaScript Document
<!DOCTYPE html>
<html>
<head>
<title>for Loop Demo</title>
</head>
<body>
<script type="text/javascript">
Days=new Array();
Days[0]="Sunday";
Days[1]="Monday";
Days[2]="Tuesday";
Days[3]="Wednesday";
Days[4]="Thursday";
Days[5]="Friday";
Days[6]="Saturday";
for(i=0;i<Days.length;i++)
{
document.write(Days[i]+"<br>");
}
</script>
</body>
</html>
Client Side Scripting Language 2-5 Array, Function and String

Output

2.1.5 Adding an Array Element


 We can add the element in the array at the end. This increases the size of the array.
 Following example illustrates this idea –

JavaScript Document
<!DOCTYPE html>
<html>
<head>
<title>for Loop Demo</title>
</head>
<body>
<script type="text/javascript">
a=new Array();
a[0]=10;
a[1]=20;
a[2]=30
a[3]=40
a[4]=50;
document.write("The elements in the array are...<br/>");
for(i=0;i<a.length;i++)
{
document.write(a[i]+" ");
}
document.write("<br/><br/>The element is added in the array...<br/>");
a[a.length]=60;
document.write("<br/>Now, The elements in the array are...<br/>");
for(i=0;i<a.length;i++)
{
document.write(a[i]+" ");
}
Client Side Scripting Language 2-6 Array, Function and String

</script>
</body>
</html>
Output

2.1.6 Sorting an Array Element


 The elements can be sorted using the built in function sort.
 Sorting is basically a process of arranging the elements in ascending order or increasing order.
 For example

JavaScript Document
<!DOCTYPE html>
<html>
<head>
<title>Sorting Demo</title>
</head>
<body>
<script type="text/javascript">
a=new Array();
a[0]=40;
a[1]=30;
a[2]=10
a[3]=50
a[4]=20;
document.write("The elements in the array are...<br/>");
for(i=0;i<a.length;i++)
{
document.write(a[i]+" ");
}
document.write("<br/><br/><b>The array is sorted...</b><br/>");
a.sort();
Client Side Scripting Language 2-7 Array, Function and String

document.write("<br/>Now, The elements in the array are...<br/>");


for(i=0;i<a.length;i++)
{
document.write(a[i]+" ");
}
</script>
</body>
</html>
Output

2.1.7 Combining Array Elements into String


 In JavaScript it is possible to combine the array elements into a string.
 We need to use two functions for combining array elements into string and those are –
1) Join() 2) concat()
 There is difference between join() and concat() function. The concat() method separates each value
with a comma. The join() method also uses a comma to separate values, but you can specify a character
other than a comma to separate values.

JavaScript Document
<!DOCTYPE html>
<html>
<head>
<title>Combing Array Demo</title>
</head>
<body>
<script type="text/javascript">
a=new Array();
a[0]="Red";
a[1]="Orange";
a[2]="Yellow"
a[3]="Green"
Client Side Scripting Language 2-8 Array, Function and String

a[4]="Blue";
a[5]="Indigo";
a[6]="Violet";
document.write("<h3> The join() method</h3>");
var str1=a.join(' ');
document.write(str1);
document.write("<h3> The concat() method</h3>");
var str2=a.concat();
document.write(str2);

</script>
</body>
</html>
Output

2.1.8 Changing Elements of an Array


There are various methods that help in changing the elements of array.

(1) Shift Method


This method removes the first element of the array. For example –
<!DOCTYPE html>
<html>
<head>
<title>Changing Array Demo</title>
</head>
<body>
<script type="text/javascript">
a=new Array();
a[0]=10
a[1]=20
a[2]=30
Client Side Scripting Language 2-9 Array, Function and String

a[3]=40
a[4]=50
document.write("<h4> The shift() method</h4>");
var num=a.shift();
document.write(num);
document.write("<h4>The elements in array are ...</h4>");
for(i=0;i<a.length;i++)
document.write(a[i]+" ");
</script>
</body>
</html>
Output

(2) Push Method


The push method is used to create a new element at the end of the array.
For example –
<!DOCTYPE html>
<html>
<head>
<title>Changing Array Demo</title>
</head>
<body>
<script type="text/javascript">
a=new Array();
a[0]=10
a[1]=20
Client Side Scripting Language 2 - 10 Array, Function and String

a[2]=30
a[3]=40
a[4]=50
document.write("<h4>The elements in array are ...</h4>");
for(i=0;i<a.length;i++)
document.write(a[i]+" ");
document.write("<h4> Calling The push() method</h4>");
a.push(60);
document.write("<h4>The elements in array are ...</h4>");
for(i=0;i<a.length;i++)
document.write(a[i]+" ");
</script>
</body>
</html>
Output

(3) Pop Method


This method returns and removes the last element of the array. For example
<!DOCTYPE html>
<html>
<head>
<title>Changing Array Demo</title>
</head>
<body>
<script type="text/javascript">
a=new Array();
Client Side Scripting Language 2 - 11 Array, Function and String

a[0]=10
a[1]=20
a[2]=30
a[3]=40
a[4]=50
document.write("<h4>The elements in array are ...</h4>");
for(i=0;i<a.length;i++)
document.write(a[i]+" ");
document.write("<h4> Calling The pop() method</h4>");
var val=a.pop();
document.write("The element returned is "+val)
document.write("<h4>The elements in array are ...</h4>");
for(i=0;i<a.length;i++)
document.write(a[i]+" ");
</script>
</body>
</html>
Output

(4) Reverse Method


The reverse method is used to reverse the elements present in the array. For example
<!DOCTYPE html>
<html>
<head>
<title>Changing Array Demo</title>
</head>
Client Side Scripting Language 2 - 12 Array, Function and String

<body>
<script type="text/javascript">
a=new Array();
a[0]=10
a[1]=20
a[2]=30
a[3]=40
a[4]=50
document.write("<h4>The elements in array are ...</h4>");
for(i=0;i<a.length;i++)
document.write(a[i]+" ");
document.write("<h4> Calling The reverse() method</h4>");
a.reverse();
document.write("<h4>The elements in array are ...</h4>");
for(i=0;i<a.length;i++)
document.write(a[i]+" ");
</script>
</body>
</html>
Output

2.1.9 Objects as Associative Array


Associative array is a specialized array in which the elements are stored in (Key,value) pair.
We can create associative array as
Client Side Scripting Language 2 - 13 Array, Function and String

JavaScript Document
<!DOCTYPE html>
<html>
<head>
<title>Associative Array Demo</title>
</head>
<body>
<script type="text/javascript">
a=new Object();
a["one"]=1;
a["two"]=2;
a["three"]=3;
a["four"]=4;
a["five"]=5;
document.write("<h4>The elements in array are ...</h4>");
for(i in a)
document.write(i+"="+a[i]+"<br/>");
</script>
</body>
</html>
Output

2.2 Function
 We can write the functions in the JavaScript for bringing the modularity in the script.
 Separate functions can be created for each separate task. This ultimately helps in finding the bug from
the program efficiently.
Client Side Scripting Language 2 - 14 Array, Function and String

2.2.1 Defining a Function


 We can define the function anywhere in the script either in head or body section or in both. But it is a
standard practice to define the function in the head section and call that function from the body
section.
 The keyword function is used while defining the function.
 The syntax for defining the function is
function name_of _function (arg1,arg2,…argn)
{

Statements
}

2.2.2 Writing a Function


Here is a simple illustration in which we have written a function my_fun()

JavaScript[FunDemo.html]

<!DOCTYPE html>
<html>
<head>
<title>Function Demo</title>
<script type="text/javascript">
function my_fun()
{
document.write("This statement is within the function"); Definition of function
}
</script>
</head>
<body>
<center>
<script type="text/javascript">
document.write("This statement is before a function call");
document.write("<br>");
my_fun(); // call to the function
</script>
</center>
</body>
</html>
Client Side Scripting Language 2 - 15 Array, Function and String

Output

Script Explanation
The above code is pretty simple. We have defined one function named my_fun in the head section of the
HTML document and called it from the body section. The corresponding write statements are used to
display the messages on the browser window.

2.2.3 Adding an Arguments


 We can pass some arguments to the function.
 The syntax is
function function_name(aregument1, argument2…,argumentn)
{
//body of function
}

2.2.4 Scope of Variable and Argument


 Scope is the block or area of program in which particular variable or argument is accessible.
 The scope is defined using two types of variables - Local Scope and Global Scope.

Local Scope
If a variable is defined inside a function then that variable is a local variable and its scope is a local scope.
That also means, that the local variable is accessible only within a function in which it is defined. It is not
accessible outside that function.
Following program shows the use of local variable.
JavaScript Example for Demonstrating scope of Local Variable
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function A()
{
Client Side Scripting Language 2 - 16 Array, Function and String

var a=100//local variable


document.getElementById("id1").innerHTML=
"From function A(): a = "+a
}
function B()
{
document.getElementById("id2").innerHTML=
"From function B(): a = "+a Output
}
</script>
</head>
<body>
<p id="id1"></p>
<p id="id2"></p>
<script type="text/javascript">
A()
B()
</script>
</body>
</html>
Script Explanation : In above JavaScript,
(1) We have created two functions namely A() and B().
(2) Inside the A() function variable a is declared and initialized to the value 100. The value of this variable
is displayed using the element<p>…</p>
(3) Inside the B() function, we are trying to display the value of same variable a using <p>…</p> . But
note that the output does not display value of variable a through function B(). This is because
variable a is a local variable declared in function A(). Hence its scope is upto the function A().
Outside this function, the variable a is undefined.

Global Variable
A variable is called global variable , if it is defined outside the function. The variable having global scope
is accessible by any function.
Following example illustrates the use of global variable.

JavaScript Example for Demonstrating the scope of Global Variable


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var a=100//Global variable
function A()
{
document.getElementById("id1").innerHTML
="From function A(): a = "+a
}
function B()
Client Side Scripting Language 2 - 17 Array, Function and String

{
document.getElementById("id2").innerHTML
="From function B(): a = "+a Output
}
</script>
</head>
<body>
<p id="id1"></p>
<p id="id2"></p>
<script type="text/javascript">
A()
B()
</script>
</body>
</html>

2.3 Calling a Function

2.3.1 Calling a Function with Argument


In JavaScript, we can pass an argument to the function. Following JavaScript shows how to pass an
argument to the function. In the following program I have written a simple function for addition of two
numbers. The values of two numbers are 10 and 20 respectively. Inside this function the addition of these
two arguments is carried out and result is displayed on the Browser page.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function add(a,b)//function to which arguments a and b are passed
{
c=a+b
document.write("Addition = "+c)
}
</script>
</head>
<body>
<h4> Passing Arguments to the function </h4>
<script type="text/javascript">
var x=10;
var y=20
add(x,y)
</script>
</body>
</html>

2.3.2 Calling a Function without an Argument


A function can also be called without passing any argument. In this case, all the required variables are
declared and used within that function. Following program shows how to call a function without
passing an argument.
Client Side Scripting Language 2 - 18 Array, Function and String

JavaScript Document
<!DOCTYPE html>
<html> Output
<head>
<script type="text/javascript">
function add()
{
var a=10
var b=20
c=a+b
document.write("Addition = "+c)
}
</script>
</head>
<body>
<h4> Function without passing argument</h4>
<script type="text/javascript">
add()
</script>
</body>
</html>

2.3.3 Calling Function from HTML


For calling a function from HTML normally, JavaScript events are used. For example –

JavaScript Document
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function A()
{
alert("Inside the function A");
}
</script>
</head>
<body onload="A()">
</script>
</body>
</html>
Client Side Scripting Language 2 - 19 Array, Function and String

Output

2.3.4 Function Calling another Function


We can call one function from another function. This is called nested functions. In the following code,
there is a call for function B() from function A().
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function A()
{
B();//calling another function
}
function B()
{
alert("Inside function B() via function A()");
}
</script>
</head>
<body onload="A()">
</script>
</body>
</html>
Client Side Scripting Language 2 - 20 Array, Function and String

Output

2.3.5 Returning a Value from Function


 We can return some value from the function using a keyword return.
 This return value is either stored in variable or directly displayed on the browser window.
 Following is a simple illustration in which the value is returned from the function and is directly
displayed on the browser window using document.write.

JavaScript[FunRetDemo.html]
<!DOCTYPE html>
<html>
<head>
<title>Function Demo</title>
<script type="text/javascript">
function my_fun()
{
str="I am function returned value";
return str;
}
</script>
</head>
<body>
<center>
<script type="text/javascript">
document.write("This statement is before a function call");
document.write("<br>");
document.write("<h3>"+my_fun()+"<h3>");
</script>
</center>
</body>
</html>
Client Side Scripting Language 2 - 21 Array, Function and String

Output

2.4 String
 String is a collection of characters.
 Some commonly used methods of string object are concatenating two strings, converting the string to
upper case or lower case, finding the substring of a given string and so on.
 The string is written within the quotes- either single quote or double quote. For example –
var myname=’ABC’

2.4.1 Manipulating a String


Manipulating a string means, changing one string to another, joining two strings, changing the string
from upper case to lower case or from lower case to upper.
There are some commonly used methods of string

Method Meaning

concat(str) This method concatenates the two strings. For example s1.concat(s2) will result in
concatenation of string s1 with s2.

charAt(index_val) This method will return the character specified by value index_val.

substring(begin,end) This method returns the substring specified by begin and end character.

toLowerCase() This function is used to convert all the uppercase letters to lower case.

toUpperCase() This function is used to convert all the lowercase letters to upper case.

valueOf() This method returns the value of the string.

There is one important property of string object and that is length. For example
var my_str=”Hello”;
Length of the string “Hello” will be
var len; stored in the variable len
len=my_str.length;
Client Side Scripting Language 2 - 22 Array, Function and String

2.4.2 Joining a String


We can join two strings using + operator. For example –
<!DOCTYPE html>
<html>
<script type="text/javascript">
var Firstname="AAA"
var Lastname=" BBB"
var name=Firstname+Lastname
alert(name);
</script>
</body>
</html>
Output

2.4.3 Receiving a Character from Given Position


The charAt() is a method that returns the character from the specified index. The index of a first character
is 0; the second character is 1, and so on. Javascript characters in a string are indexed from left to right.
If no index is provided to charAt() method, then the default is 0. Following program illustrates how to
receive character from given position.

JavaScript Document
<!DOCTYPE html>
<html>
<script type="text/javascript">
var str="ABC"
alert("The character at first position of string: "+str+" is: "+str.charAt(0))
</script>
</body>
</html>
Client Side Scripting Language 2 - 23 Array, Function and String

Output

2.4.4 Retrieving a Position of Character in a String


 For finding the position of particular character we use indexOf function.
 It returns the position of the first occurrence of a specified value in a string.
 This method is case sensitive.
 Example
<!DOCTYPE html>
<html>
<script type="text/javascript">
var str="I love India - my country"
var n=str.indexOf("India");
alert("The word 'India' is from index: "+n+" in the text: "+str)
</script>
</body>
</html>
Output
Client Side Scripting Language 2 - 24 Array, Function and String

2.4.5 Dividing Text


 Any text is made up of words. We can divide the text into a collection of these words. For example –
User may enter his/her complete name as first name, middle name and surname. By dividing the text,
we can get firstname, middle name and surname separated.
 Usually split() function is used to divide the text.
 The split() method creates a new array and then copies portions of the string, called a substring, into
its array element.
 Syntax : The split method is used in the following manner –
var newStrArray=textname.split(delimiter character)

JavaScript Document
<!DOCTYPE html>
<html>
<script type="text/javascript">
var Name="Shivaji Shahaji Bhosale"
var list=Name.split(' ')
alert("First Name: "+list[0]+"\nMiddle Name: "+list[1]+"\nLast Name: "+list[2])
</script>
</body>
</html>
Output

2.4.6 Copying a Substring


There are two useful methods for copying a substring – i) substring() and ii) substr()

1. Use of substring
The syntax of substring is
substring(start, end)
where start indicates the starting index and end indicates the ending index for extracting substring.
Client Side Scripting Language 2 - 25 Array, Function and String

Following program shows use of substring() function for retrieving the substring and then copying it to
some other string at the end.
<!DOCTYPE html>
<html>
<script type="text/javascript">
var Name1="Shivaji Shahaji Bhosale"
var Name2="Sambhaji"
var sub_str=Name1.substring(16,23)
document.write("<br/>The Name1: "+Name1)
document.write("<br/>The Surname: "+sub_str)
document.write("<br/>The Name2: "+Name2)
document.write("<br/><b>Copying the surname for Name2...</b>")
var Name3=Name2+" "+sub_str
document.write("<br/>The Name3: "+Name3)
</script>
</body>
</html>
Output

2. Use of substr
The substr method is also used to extract the substring from the text. The syntax for substr is as follows
substr(start,length)
where start indicates the starting index and length indicates the number of characters to be extracted.
Following example shows how to extract some substring using substr() method and then copy this
substring to another text.
JavaScript Document
<!DOCTYPE html>
<html>
<script type="text/javascript">
var Name1="Shivaji Shahaji Bhosale"
Client Side Scripting Language 2 - 26 Array, Function and String

var Name2="Sambhaji"
var sub_str=Name1.substr(16,7)
document.write("<br/>The Name1: "+Name1)
document.write("<br/>The Surname: "+sub_str)
document.write("<br/>The Name2: "+Name2)
document.write("<br/><b>Copying the surname for Name2...</b>")
var Name3=Name2+" "+sub_str
document.write("<br/>The Name3: "+Name3)
</script>
</body>
</html>
Output

2.4.7 Converting String to Number and Number to String

1. Converting String to Number


For converting string to number we have different types of functions based on type of numbers – That
means if string is to be converted to integer(a number without decimal point) then the method parseInt()
is used. If string is to be converted to float value then the method parseFloat() is used.
Example
<!DOCTYPE html>
<html>
<script type="text/javascript">
var str="100";
var a=parseInt(str)//converting string 100 to number 100
var b=200;
result=str+b
document.write("<br/>Adding 200 to '100' = "+result)
result=a+b
document.write("<br/>Adding 200 to 100 = "+result)
</script>
</body>
</html>
Client Side Scripting Language 2 - 27 Array, Function and String

Output

2. Converting Number to String


Using toString() method we can convert a number to string. For example
<!DOCTYPE html>
<html>
<script type="text/javascript">
var num=100;
var str=num.toString()
document.write("<br/>The 100 value is converted to string "+str)
</script>
</body>
</html>
Output
Client Side Scripting Language 2 - 28 Array, Function and String

2.4.8 Changing Case of String


Using toLowerCase(), we can convert the capital letters in the string to small letter. For example
<!DOCTYPE html>
<html>
<script type="text/javascript">
var str="WELCOME FRIENDS";
var newstr=str.toLowerCase()
document.write("<br/>The "+str+" is converted to: "+newstr)
</script>
</body>
</html>
Output

Using toUpperCase() method we can convert the small letters to capital letters.
For example –
<!DOCTYPE html>
<html>
<script type="text/javascript">
var str="welcome friends";
var newstr=str.toUpperCase()
document.write("<br/>The "+str+" is converted to: "+newstr)
</script>
</body>
</html>
Client Side Scripting Language 2 - 29 Array, Function and String

Output

2.4.9 Finding Unicode of a Character


 Computer can not understand characters. It understands only numbers. Hence whenever user types some
letter, it gets converted automatically to a number called Unicode number. The computer can
understand this Unicode number only.
 Unicode is a standard that assigns a number to every character, number, and symbol that can be
displayed on a computer screen.
 The charCodeAt() is a methods that returns Unicode of a string. For example –
<!DOCTYPE html>
<html>
<script type="text/javascript">
var ch='a'
var n=ch.charCodeAt()
document.write("<br/>The letter '"+ch+"' has a unicode as: "+n)
</script>
</body>
</html>
Output
 Similarly,we can obtain the letter or character from a Unicode using the method fromCharCode(). For
example
<!DOCTYPE html>
<html>
<script type="text/javascript">
var n=97
var ch=String.fromCharCode(n)
document.write("<br/>The unicode "+n+" is for letter : "+ch)
</script>
</body>
</html>
Output

You might also like