0% found this document useful (0 votes)
1 views64 pages

Unit II Array, Function and String

Uploaded by

riyasonawane2306
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views64 pages

Unit II Array, Function and String

Uploaded by

riyasonawane2306
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT II: ARRAY, FUNCTION &

STRING

MR. S. P. KHOLAMBE
LECTURER IN CO DEPTT.,
MET BKC IOTP NASHIK
Array

 The Array object lets you store multiple values in a single


variable.
 It stores a fixed-size sequential collection of elements of the
same type.
 An array is used to store a collection of data, but it is often more
useful an array as a collection of variables of the same type.

2
Declaring an Array

 In JavaScript the array can be created using Array object.


 Syntax:
var a = new Array(10);
 In above syntax array is created of 10 elements.
 Using new operator we can allocate the memory dynamically
for the arrays.
 We can also define array by following ways:
var fruits = new Array( "apple", "orange", "mango" );

3
Initializing an Array

 Initializing is the process of assigning a value when either a


variable or array is declared.
 Example: int count= 20// variable initialization.

 While initializing an array:


1. Declare name of the array
2. Make use of the keyword new
3. Each value in array as an array element & separated by comma.
 Example: var mylist= new Array(20,40,50,60)

4
Defining An Array Elements

 The element of an array are stored from index 0.


 Example: Element in array 1,3,5,2,4 are stored as follows-

5
JavaScript to display array element.

<html>
<body> Output:
<script>
[Link]("Array is :"+ "<br/>");
var a=[10,20,30,40]; Array is :
for (i=0; i<[Link]; i++){ 10
[Link](a[i] + "<br/>"); 20
} 30
</script> 40
</body>
</html>
JavaScript to returns the length of the array.

<html>
<head>
<title>JavaScript Array length Property</title>
</head>
<body>
<script type = "text/javascript">
var arr = new Array( 10, 20, 30 );
[Link]("The Length of array is : " + [Link]);
</script>
</body>
</html>

Output:
The Length of array is : 3
Looping in Array

 Looping an array means visiting each element present in the


array.
<html>
<body>
<script>
var i;
[Link]("Weekdays are:" + "<br>");
Days = new Array();
Days[0] = "Sunday";
Days[1] = "Monday"; Output:
Days[2] = "Tuesday";
Days[3] = "Wednesday"; Weekdays are:
Days[4] = "Thursday";
Sunday
Days[5] = "Friday";
Monday
Days[6] = "Saturday";
for (i=0;i<[Link];i++){ Tuesday
[Link](Days[i] + "<br>"); Wednesday
} Thursday
</script> </body> </html> Friday
Saturday
Adding An Array Element

 We can add element in the array at the end. This increase the
size of the array.
<html>
<body>
<script>
var i;
a = new Array();
a[0] = 10;
a[1] = 20;
a[2] = 30;
[Link]("The elements are in array:" + "<br>");
for (i=0;i<[Link];i++){
[Link](a[i] + "<br>");
}
[Link]("The elements is added in array:" + "<br>");
a[[Link]]=70;
[Link]("The array after element added....." + "<br>");
for (i=0;i<[Link];i++){
[Link](a[i] + "<br>");
}
</script> </body> </html>
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
descending ding order or descending order.
<html> <body> <script>
var i;
a = new Array();
a[0] = 20;
a[1] = 30;
a[2] = 50;
a[3] = 15;
a[4] = 10;
a[5] = 75;
[Link]("The elements are in array:" + "<br>");
for (i=0;i<[Link];i++){
[Link](a[i] + "<br>");
}
[Link]("The array is sorted....." + "<br>");
[Link]();
[Link]("The array after Sorting....." + "<br>");
for (i=0;i<[Link];i++){
[Link](a[i] + "<br>");
}
</script> </body> </html>
Combining An Array Element Into A String

 In JavaScript it is possible to combine the array elements into a


string.
 For combining array elements into string we can use join() &
concat() function.
<html>
<head> Output
<title>JavaScript Array join Method</title>
</head>
<body>
str : First,Second,Third
<script type = "text/javascript"> str : First, Second, Third
var arr = new Array("First","Second","Third"); str : First + Second + Third
var str = [Link]();
[Link]("str : " + str );

var str = [Link](", ");


[Link]("<br />str : " + str );

var str = [Link](" + ");


[Link]("<br />str : " + str );
</script>
</body>
</html>
Changing elements of an Array

Shift Method:
 JavaScript array shift()method removes the first element from
an array and returns that element.
 Syntax: [Link]();
<html>
<head> Output
<title>JavaScript Array shift Method</title>
</head> Removed element is : 105
<body> Array element is :
<script type = "text/javascript"> 1
a = new Array(); 2
a[0]= 105; 3
a[1]=1;
a[2]=2;
a[3]=3;
var num=[Link]();
[Link]("Removed element is : " + num + "<br>");
[Link]("Array element is : " + "<br>");
for (i=0;i<[Link];i++){
[Link](a[i] + "<br>");
}
</script> </body> </html>
Changing elements of an Array

Push Method:
 JavaScript array push() method appends the given element(s)
in the last of the array and returns the length of the new array.
 Syntax: [Link](element1, ..., elementN);
<html>
<head>
<title>JavaScript Array push Method</title>
</head>
<body>
<script type = "text/javascript">
var numbers = new Array(1, 4, 9);
var length = [Link](10);
[Link]("New numbers is : " + numbers );
length = [Link](20);
[Link]("<br />New numbers is : " + numbers );
</script>
</body>
</html>

Output:
New numbers is : 1,4,9,10
New numbers is : 1,4,9,10,20
Changing elements of an Array

Pop Method:
 Javascript array pop() method removes the last element from
an array and returns that element.
 Syntax: [Link]();
<html>
<head>
<title>JavaScript Array pop Method</title>
</head>
<body>
<script type = "text/javascript">
var numbers = [1, 4, 7, 9];
var element = [Link]();
[Link]("Element after pop method : " + element );
var element = [Link]();
[Link]("<br />Element after pop method : " + element );
</script>
</body>
</html>

Output:
Element after pop method : 9
Element after pop method : 7
Changing elements of an Array

Reverse Method:
 Javascript array reverse() method reverses the element of an
array. The first array element becomes the last and the last
becomes the first.
 Syntax: [Link]();
<html>
<head>
<title>JavaScript Array reverse Method</title>
</head>
<body>
<script type = "text/javascript">
var arr = [0, 1, 2, 3].reverse();
[Link]("Reversed array is : " + arr );
</script>
</body>
</html>

Output:
Reversed array is : 3,2,1,0
Object As Associative Array

 An associative array is simply a set of key value pairs.


 The value is stored in association with its key and if you
provide the key the array will return the value.
 This is all an associative array is and the name comes from the
association between the key and the value.
 The key is a sort of generalized address that can be used to
retrieve the stored value.
 For example: array = {key1: 'value1',key2:'value2'};
<html>
<head>
<title>JavaScript Array pop Method</title>
</head>
<body>
<script type = "text/javascript">
var o = new Object(); Output:
[Link]( "Associative Array is :" + "<br>");
o["One"] = 1;
o["Two"] = 2;
Associative Array is
o["Three"] = 3; :
o["Four"] = 4 One=1
for(var i in o)
{ Two=2
[Link](i + "=" + o[i] + '<br>'); Three=3
}
</script>
Four=4
</body>
</html>
Function

 A function is a group of reusable code which can be called


anywhere in your program.
 This eliminates the need of writing the same code again and
again.
 It helps programmers in writing modular codes.
 Functions allow a programmer to divide a big program into a
number of small and manageable functions.
Declaring A Function

 Before we use a function, we need to define it. The most common


way to define a function in JavaScript is by using the function
keyword, followed by a unique function name, a list of
parameters (that might be empty), and a statement block
surrounded by curly braces.
 Syntax:
function functionname(parameter-list)
{
statements
}
<html> Writing a Function
<head>
<script type = "text/javascript">
function sayHello()
{
[Link] ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello">
</form>
</body>
</html>
Adding An Arguments

 We can pass some arguments to the function.


 Syntax:
function functionname(argument1, argument2,….. argumentn)
{
statements
}
Scope Of Variable & Arguments

 Scope is the block of program in which particular variable or


arguments is accessible.
 Scope is defined using two types: Local & Global
Scope/Variable.

 Local Variables − A local variable will be visible only within a


function where it is defined. Function parameters are always
local to that function.
 Global Variables − A global variable has a global scope which
means it can be defined anywhere in your JavaScript code.
<html>
<body onload = checkscope();>
<script>
var myVar = "Global"; // Declare a global variable
function checkscope( ) {
// var myVar = "Local"; // Declare a local variable
[Link]("Variable is : "+ myVar);
}
</script>
</body>
</html>
Output: Variable is : Global
Calling A Function With An Argument

 A function can also be called without passing any argument.


<html>
<head>
<script type = "text/javascript">
function sayHello(marks)
{
[Link] ("Marks is : " + marks);
}
</script>
</head>
<body onload = sayHello(100);>
</body>
</html>
Output: Marks is : 100;
Calling A Function Without An Argument

 These passed argument can be captured inside the function and


any manipulation can be done over those argument.
 A function can take multiple argument separated by comma.
<html>
<head>
<script type = "text/javascript">
function sayHello()
{
[Link] ("A Function Without An Argument.....");
}
</script>
</head>
<body onload = sayHello();>
</body>
</html>
Output: A Function Without An Argument.....
Calling Function From HTML
<html>
<head>
<script type = "text/javascript">
function myFunction(a, b) {
num=a * b;
[Link] ("Value of Num : "+num);
}
</script>
</head>
<body onload = myFunction(10,20);>
</body>
</html>
Function Calling Another Function

 We can call one function from another function. This is called


nested function.
<html>
<head>
<script type = "text/javascript">
function Calling() {
[Link] ("Inside Calling Function...");
}
function Caller()
{
[Link] ("Inside Caller Function..."+ "</br>");
Calling();
}
</script>
</head>
<body onload = Caller();>
</body> </html>
Returning A Value From A Function

 A JavaScript function can have an optional return statement.


 This is required if you want to return a value from a function.
 This statement should be the last statement in a function.
 The return value is either stored in variable or directly display
in browser.
<html>
<head>
<script type = "text/javascript">
var x = myFunction(4, 3);
[Link]("Value is : "+ x)
function myFunction(a, b) {
return a * b;
}
</script>
</head>
<body onload = myFunction(a,b);>
</body>
</html>
String

 String is a collection of characters.


 Commonly used method of string object are concatenating two
strings, converting the string to upper case or lower case, finding
the substring of a given string.
 String written within the single or double quotes.
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.
1. charAt() :Returns the character at the specified index.
2. charCodeAt(): Returns a number indicating the Unicode value of the
character at the given index.
3. concat():Combines the text of two strings and returns a new string.
4. indexOf():Returns the index within the calling String object of the first
occurrence of the specified value, or -1 if not found.
5. lastIndexOf():Returns the index within the calling String object of the
last occurrence of the specified value, or -1 if not found.
Joining A String

 This method adds two or more strings and returns a new


single string.
 Syntax: [Link](string2, string3[, ..., stringN]);
 string2...stringN − These are the strings to be concatenated.
<html>
<body>
<script>
function func()
{
var str = 'It';
var value = [Link](' is',' a',' great',' day.');
[Link](value);
}
func();
</script> </body> </html>
Output: It is a great day.
Retrieving A Character From Given Position

 charAt() is a method that returns the character from the


specified index.
 Characters in a string are indexed from left to right. The index of
the first character is 0, and the index of the last character in a
string, called stringName, is [Link] – 1.
 Syntax: [Link](index);
 index − An integer between 0 and 1 less than the length of the
string.
<html>
<body>
<script type = "text/javascript">
var str = new String( "MET Polytechnic" );
[Link]("[Link](0) is:" + [Link](0));
[Link]("<br />[Link](1) is:" + [Link](1));
[Link]("<br />[Link](2) is:" + [Link](2));
[Link]("<br />[Link](4) is:" + [Link](4));
[Link]("<br />[Link](5) is:" + [Link](5));
</script>
</body>
</html>
Retrieving A Position Of Character In A String

 JavaScript array indexOf() method returns the first index at


which a given element can be found in the array, or -1 if it is not
present..
 Syntax: string. indexOf(string);
<html>
<body>
<script type = "text/javascript">
var str1 = new String( "This is string one" );
var index = [Link]( "string" );
[Link]("indexOf found String :" + index );
[Link]("<br />");
var index = [Link]( "one" );
[Link]("indexOf found String :" + index );
</script>
</body>
</html>
Dividing Text

 This method splits a String object into an array of strings by


separating the string into substrings.
 Syntax: [Link]([separator][, limit]);
 separator − Specifies the character to use for separating the string.
If separator is omitted, the array returned contains one element
consisting of the entire string.
 limit − Integer specifying a limit on the number of splits to be found.
<html>
<body>
<script type = "text/javascript">
var str = "MET Bhujbal Knowledge City Nashik.";
var splitted = [Link](" ", 3);
[Link]( splitted );
</script>
</body>
</html>

Output: MET,Bhujbal,Knowledge
Copying a Substring (Using of substr)

 This method returns the characters in a string beginning at


the specified location through the specified number of
characters.
 Syntax: [Link](start[, length]);
 start − Location at which to start extracting characters (an integer
between 0 and one less than the length of the string).
 length − The number of characters to extract.
<html>
<body>
<script type = "text/javascript">
var str = "MET Bhujbal Knowledge City Nashik.";
[Link]("(1,2): " + [Link](1,2));
[Link]("<br />(-2,2): " + [Link](-2,2));
[Link]("<br />(1): " + [Link](1));
[Link]("<br />(-10, 2): " + [Link](-10,2));
[Link]("<br />(10, 2): " + [Link](10,2));
</script>
</body>
</html>
Copying a Substring (Using of substring)

 This method returns a subset of a String object.


 Syntax: [Link](indexA, [indexB])
 indexA − An integer between 0 and one less than the length of the
string.
 indexB − (optional) An integer between 0 and the length of the
string.
<html>
<body>
<script type = "text/javascript">
var str = "MET Bhujbal Knowledge City Nashik.";
[Link]("(1,4): " + [Link](1,4));
[Link]("<br />(0,15): " + [Link](0, 21));
[Link]("<br />(5): " + [Link](5));
</script>
</body>
</html>
Converting String To Number

 Converting string to number we have different types of function


based on type of numbers i.e. string is to be converted to
integer by using parseInt( ) method.
 If string is to be converted to float value then the method
parseFloat().
<html>
<body>
<script type = "text/javascript">
var str = "100";
var a = parseInt(str);
var b=200;
result= str+b
[Link]("<br/> Adding 200 to '100' ="+result);
result= a+b
[Link]("<br/> Adding 200 to 100 ="+result);
</script>
</body>
</html>
Converting Number To String

 This method returns a string representing the specified object.


 Syntax: [Link]( )
 Returns a string representing the specified object.
<html>
<body>
<script type = "text/javascript">
var str = "MET Bhujbal Knowledge City Nashik.";
[Link]([Link]( ));
</script>
</body>
</html>
Changing The Case Of String

 This method returns the calling string value converted to


lowercase.
 Syntax: [Link]( )

 This method returns the calling string value converted to


uppercase.
 Syntax: [Link]( )
<html>
<body>
<script type = "text/javascript">
var str = "MET Bhujbal Knowledge City Nashik.";
[Link]("String is : "+[Link]( ));
var s1= "met bhujbal knowledge city nashik.";
[Link]("<br/>" +"String is : "+ [Link]( ));
</script>
</body>
</html>
Changing The Case Of String

 This method returns a number indicating the Unicode value of


the character at the given index.
 Unicode code points range from 0 to 1,114,111. The first 128
Unicode code points are a direct match of the ASCII character
encoding. charCodeAt() always returns a value that is less than
65,536.
 Syntax: [Link](index);
 index − An integer between 0 and 1 less than the length of the
string; if unspecified, defaults to 0.
<html>
<body>
<script type = "text/javascript">
var str = new String( "MET Bhujbal Knowledge City Nashik." );
[Link]("[Link](0) is:" + [Link](0));
[Link]("<br />[Link](1) is:" + [Link](1));
[Link]("<br />[Link](7) is:" + [Link](7));
[Link]("<br />[Link](3) is:" + [Link](3));
[Link]("<br />[Link](4) is:" + [Link](4));
[Link]("<br />[Link](19) is:" + [Link](10));
</script>
</body>
</html>

You might also like