Unit 2 - Array - Function - String
Unit 2 - Array - Function - String
Unit 2
Array, Function and String
Marks: 14 (R-2, U-4, A-8)
Unit Outcome:
1
Client-Side Scripting (Semester-V)
2. Introduction
2.1 Array
Array is used to store a set of values (different types) in a single
variable name.
Arrays are the fundamentals part of the most programming languages
and scripting languages.
Using array, we can store multiple values under a single name.
You can declare an array with the “new” keyword to instantiate the array in
memory.
2
Client-Side Scripting (Semester-V)
In this form, the constructor arguments become the elements of the new
array.
When we declare array using square brackets is called the “array literal
notation”:
Var x= [];
Var x=[5];
When initializing an array, you place the value within the parentheses of the
Array() constructor.
The following example initializes the products array with the value 'BMW',
which is assigned to the first element of this array:
In the real world, an array usually has more than one array element, with
each
element having its own value. Therefore, you’ll find yourself having to
initialize the array with more than one value.
Here’s how this is done:
var products = new Array('BMW', 'Maruti', 'Mahindra')
3
Client-Side Scripting (Semester-V)
while Initializing array with declaration then all elements must specify in
parenthesis and elements should be separated by a comma.
Code:
<html>
<head>
<title>Array</title>
</head>
<body>
<script>
var products = new Array('BMW', 'Maruti', 'Mahindra');
document.write(“Length of array is :”+products.length);
</script>
</body>
</html>
Output:
Length of array is : 3
cars[0] = “BMW”;
cars[1] = “Maruti”;
cars[2] =2546 ;
Accessing an array value is quite easy. We use array index to access a value.
If we want to access val 1 from the above syntax , we use Array[0], So,
4
Client-Side Scripting (Semester-V)
Code:
<html>
<head>
<title> Array</title>
</head>
<body>
<script>
var cars = new Array(3);
cars[0] = “BMW”;
cars[1]=”Maruti”;
cars[2]=”Honda”;
document.write(cars[0]);
document.write(“<br>”+ cars[1]);
document.write(“<br>”+ cars[2]);
</script>
</body></html>
Output:
BMW
Maruti
Honda
5
Client-Side Scripting (Semester-V)
Loops are handy, if you want to run the same code over and over again, each
time with a different value. We can use arrays within loops and access array
elements using loops in JavaScript.
To identify how many loops, we must know the total number of elements
present inside the array which can find out using array_name.length.
Example:
<html>
<body>
<h2>JavaScript For Loop</h2>
<script>
var cars = ["BMW", "Volvo", "Ford", "Fiat"];
var text = "";
var i;
for (i = 0; i < cars.length; i++)
{
document.write(cars[i]+"<br>");
}
</script>
</body>
</html>
Output:
BMW
Volvo
Ford
Fiat
6
Client-Side Scripting (Semester-V)
On some occasions your JavaScript will need to increase the size of the array
while your JavaScript is running.
There are two methods to add the elements into the array:
Method1:
The easiest way to add a new element to an array is using the push()
method.
The push() method adds new items to the end of an array, and returns the
new length.
Syntax:
array.push(item1, item2, ..., itemX);
Example:
var fruits = [ "Banana", "Orange", "Apple", "Mango” ];
fruits.push( "Lemon” ); // adds a new element (Lemon) to fruits
Method 2:
The unshift() method adds one or more elements to the beginning of an
array and returns the new length of the array.
.
Syntax:
array.unshift(item1, item2, ..., itemX);
Example:
var fruits = [ "Banana", "Orange", "Apple", "Mango” ];
fruits.unshift( "Lemon","Pineapple” );
Example:
<html>
<head>
<title> Array</title>
<body>
<script>
var fruits = new Array(3);
fruits[0] = "Banana";
fruits[1] = "Orange";
fruits[2] = "Apple";
fruits[3] = "Mango";
for(i=0;i<fruits.length;i++)
{
document.write(fruits[i] +" "+"<br>");
7
Client-Side Scripting (Semester-V)
fruits.push("Lemon");
fruits.unshift("Pineapple");
for(i=0;i<fruits.length;i++)
{
document.write(fruits[i] +" ");
}
</script>
</body>
</html>
Output
The index of the array elements determines the order in which values appear
in an array when a for loop is used to display the array. Sometimes you want
values to appear in sorted order, which means that strings will be presented
alphabetically and numbers will be displayed in ascending order. You can
place an array in sorted order by calling the sort() method of the array
object. The sort() method reorders values assigned to elements of the array,
regardless of the index of the element to which the value is assigned.
Here’s what you need to do to sort an array:
1. Declare the array.
2. Assign values to elements of the array.
3. Call the sort() method.
Example:
<html>
8
Client-Side Scripting (Semester-V)
<body>
<script>
Output:
Fan
Pizza
Soap
Water
Example:
<html>
<body>
<script>
var fruits = ["Banana", "Watermelon", "Chikoo", "Mango", "Orange",
"Apple"];
fruits.sort();
document.write(fruits+"<br>");
9
Client-Side Scripting (Semester-V)
fruits.reverse();
document.write(fruits+"<br>");
</script>
</body>
</html>
Output:
Apple,Banana,Chikoo,Mango,Orange,Watermelon
Watermelon,Orange,Mango,Chikoo,Banana,Apple
car[0] = “BMW”;
car[1] = “Maruti”;
car[2] = “Honda”;
The concat() method separates each value with a comma. It is used to join
one or more arrays.
Syntax:
array.concat()
Example:
var CO_Subject = ["PHP", "CSS", "Java"];
var Math_Subject= ["Applied Math", "Elements of Maths"];
var subjects = CO_Subject.concat(Math_Subject);
document.write(subjects);
Output:
PHP,CSS,Java,Applied Math,Elements of Maths
10
Client-Side Scripting (Semester-V)
Syntax: array.join(separator);
Parameters: *
Separator: It is Optional.
it can be either used as parameter or not. Its default value is comma(, ).
Example:
<html>
<body>
<script>
Car,Water,Soap,Pizza
11
Client-Side Scripting (Semester-V)
The shift() method removes the first element of the array then moves the
other tasks up on the list and returns the removed item.
Example:
<html>
<head>
<title> Array</title>
</head>
<body>
<script>
Var car = new Array(3);
car[0]=”BMW”;
car[1]=”Honda”;
car[2]=”Maruti”;
car.shift();
for (i=0;i<car.length;i++)
{
document.write(items[i]+””);
}
</script>
</body>
</html>
Output:
Honda Maruti
12
Client-Side Scripting (Semester-V)
Example:
<html>
<head>
<title> Array</title>
</head>
<body>
<script>
Var car = new Array(3);
car[0]=”BMW”;
car[1]=”Honda”;
car[2]=”Maruti”;
car.pop();
for (i=0;i<car.length;i++)
{ document.write(items[i]+””);
}</script>
</body>
</html>
Output:
BMW Honda
The splice() method can be used to add new items to an array, and removes
elements from an array.
Syntax:
arr.splice(start_index,removed_elements,list_of_elemnts_to_be_added);
Parameter:
•The first parameter defines the position where new elements should be
added (spliced in).
•The second parameter defines how many elements should be removed.
•The list_of_elemnts_to_be_added parameter define the new elements to be
added(optional).
Example:
13
Client-Side Scripting (Semester-V)
<html>
<body>
<script>
var fruits = ["Banana", "Watermelon", "Chikoo", "Mango", "Orange",
"Apple"]; document.write(fruits+"<br>");
fruits.splice(2,2, "Lemon", "Kiwi");
document.write(fruits+"<br>");
fruits.splice(0,2); //removes first 2 elements from array
document.write(fruits+"<br>");
</script>
</body>
</html>
Output:
Banana,Watermelon,Chikoo,Mango,Orange,Apple
Banana,Watermelon,Lemon,Kiwi,Orange,Apple
Lemon,Kiwi,Orange,Apple
The slice() method slices out a piece of an array into a new array.
Parameter:
•slices out a part of an array starting from array element 1.
Example:
<html>
<body>
<script>
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
document.write(fruits);
var citrus = fruits.slice(2);
document.write("<br>"+citrus);
</script>
</body>
</html>
14
Client-Side Scripting (Semester-V)
Output:
Banana,Orange,Lemon,Apple,Mango
Lemon,Apple,Mango
Thus, the following two JavaScript expressions have the same value:
object.property ;
object["property"] ;
objectName["propertyName" ] ;
Example:
<html>
<body>
<script>
var object1 = new Object;
object1.name = “abc";
object1.nationality = "Indian";
document.write(" property name: " + object1["name"] );
document.write("<br>");
document.write(" property nationality: " + object1["nationality" ] );
</script>
</body>
</html>
OUTPUT :
property name: Girija
property nationality: Indian
15
Client-Side Scripting (Semester-V)
<html>
<body>
<script>
var arr = new Array();
arr.push(1,2,3);
arr.push(5,6);
document.write("After the Join method" +arr.join(","));
arr.pop();
document.write("<br>After the pop method" +arr.join(","));
arr.shift();
document.write("<br>After the shift method" +arr.join(","));
arr.reverse();
document.write("<br>After the reverse method"+arr.join(","));
arr.unshift(1);
16
Client-Side Scripting (Semester-V)
</script>
</body>
</html>
Output:
2-Dimensional Array:
Example:
var branch = [
['Computer Engg', "CO"],
['Information Technology', "IF"],
['Electronics and Telecommunication', "EJ"] ];
<script>
var branch = [
['Computer Engg', "CO"],
['Information Technology', "IF"],
['Electronics and Telecommunication', "EJ"],
['Civil Engineering', "CV"],
['Chemical Engg', "CE"],
['Instrumnet Engg',"IE"]
17
Client-Side Scripting (Semester-V)
];
// display now
for(i = 0; i < branch.length; i++)
document.write(branch[i][0] + ',' + branch[i][1] + '<br>' );
</script>
Output:
Computer Engg,CO
Information Technology,IF
Electronics and Telecommunication,EJ
Civil Engineering,CV
Chemical Engg,CE
Instrumnet Engg,IE
Multi-Dimensional Array:
Multidimensional arrays are not directly provided in JavaScript. If we want to
use anything which acts as a multidimensional array then we need to create
a multidimensional array by using another one-dimensional array. So
multidimensional arrays in JavaScript is known as arrays inside another
array. We need to put some arrays inside an array, then the total thing is
working like a multidimensional array. The array, in which the other arrays
are going to insert, that array is use as the multidimensional array in our
code. To define a multidimensional array, its exactly the same as defining a
normal one-dimensional array.
Example:
<script>
var my_ans = new Array(); // declaring array
my_ans.push({0:45,1:55,2:65,3:45});
my_ans.push({0:145,1:155,2:165,3:"VP"});
my_ans.push({0:245,1:255,2:265});
my_ans.push({0:"aaa",1:"bbb",2:"ccc",3:"ddd"});
18
Client-Side Scripting (Semester-V)
for(i=0;i<4;i++)
{
document.write("key : " + i + " =>value: " + my_ans[i][0] +
',' +my_ans[i][1] + ',' +my_ans[i][2]+ ',' +my_ans[i][3] + "<br>");
}
</script>
Output:
2.2 Function
Functions are building blocks of any programming language. Function is a
block of statements that perform certain task.
1. Built-in functions are the functions that are already defined in the
JavaScript. Example are write(), prompt() etc.
19
Client-Side Scripting (Semester-V)
Function Name
The function name is the name that you’ve assigned the function. It is placed
at the
top of the function definition and to the left of the parentheses. Any name
will do,
as long as it follows certain naming rules. The name must be
Letter(s), digit(s), or underscore character
Unique to JavaScript on your web page, as no two functions can have
the
same name
Parentheses
Parentheses are placed to the right of the function name at the top of
the function definition.
Parentheses are used to pass values to the function; these values are
called arguments.
Code Block
The code block is the part of the function definition where you insert
JavaScript statements that are executed when the function is called by
another part of your JavaScript application.
Open and close French braces define the boundaries of the code block.
Statements that you want executed must appear between the open
and close French braces.
Return (Optional)
The return keyword tells the browser to return a value from the
function definition to the statement that called the function.
20
Client-Side Scripting (Semester-V)
function function_name(parameters…)
{
Statements ….
}
Example:
function hellojavascript()
{
alert(“hello”);
}
Syntax:
Example:
<html>
<body>
<h1>Demo: JavaScript function parameters</h1>
<script>
function ShowMessage(firstName, lastName)
21
Client-Side Scripting (Semester-V)
{
alert("Hello " + firstName + " " + lastName)
}
ShowMessage("Steve", "Jobs");
</script>
</body>
</html>
The scope of a variable means how the different parts of the program
can access that variable. In JavaScript there are two types of Scope
namely: Local Scope and Global Scope.
A variable can be declared within a function this is called a local
variable, because the variable is local to the function. Other parts of
your JavaScript don’t know that the local variable exists because it’s
not available outside the function.
But a variable can be declared outside a function. Such a variable is
called a
global variable because it is available to all parts of your JavaScript—
that is, statements within any function and statements outside the
function can use a global variable.
JavaScript developers use the term scope to describe whether a
statement of a JavaScript can use a variable. A variable is considered
in scope if the statement can access the variable. A variable is out of
scope if a statement cannot access the variable.
22
Client-Side Scripting (Semester-V)
function myFunction()
{
// code here can also use carName
}
You call a function any time that you want the browser to execute
statements contained in the code block of the function.
A function is called by using the function name followed by
parentheses. If the function has arguments, values for each argument
are placed within the parentheses.
You must place these values in the same order that the arguments are
listed in the function definition. A comma must separate each value.
Here is an example of how to define and call a function that does not
have any arguments.
The function definition is placed within the <head> tag and the
function call is placed within the <body> tag.
When the function is called, the browser goes to the function definition
and executes statements within the code block of the function.
Example:
<html>
<body>
<script>
function IncreaseSalary()
{
var salary = 500000 * 1.25;
alert('Your new salary is ' + salary);
}
IncreaseSalary();
</script>
</body>
</html>
23
Client-Side Scripting (Semester-V)
Output:
The Salary and Increase variables are then used within the
parentheses of
the function call, which tells the browser to assign these values to the
corresponding arguments in the function definition. The function
calculates and displays the new salary.
Example:
<html>
<body>
<script>
function IncreaseSalary(OldSalary, PercIncrease)
{
var NewSalary =
OldSalary * (1 + (PercIncrease / 100))
alert("Your new salary is " + NewSalary)
}
var Salary = prompt('Enter old salary.', ' ')
var Increase =
prompt('Enter salary increase as percent.', ' ')
IncreaseSalary(Salary, Increase)
</script>
</body>
</html>
24
Client-Side Scripting (Semester-V)
Output:
A function can be called from HTML code on your web page. Typically,
a function will be called in response to an event, such as when the web
page is loaded or unloaded by the browser.
You call the function from HTML code nearly the same way as the
function is called from within a JavaScript, except in HTML code you
assign the function call as a value of an HTML tag attribute.
<html>
<script >
25
Client-Side Scripting (Semester-V)
function WelcomeMessage()
{
alert('Glad to see you.')
}
function GoodbyeMessage()
{
alert('So long.')
}
</script>
<body onload="WelcomeMessage()"
onunload="GoodbyeMessage()">
</body>
</html>
Output:
26
Client-Side Scripting (Semester-V)
<html>
<head>
<title> function calling another function </title>
<script>
function Logon()
{
var userID;
var password;
var valid;
userID=prompt('Enter user ID', ' ');
password=prompt('Enter Password', ' ');
valid=validateLogon(userID, password);
if(valid === true)
{
alert("Valid Logon");
}
else
{
alert("InValid Logon");
}
}
function validateLogon(id, pwd)
{
var ret_val;
if(id === '111' && pwd === 'aaa')
{
ret_val=true;
}
else
{
ret_val=false;
}
return ret_val;
27
Client-Side Scripting (Semester-V)
}
</script>
</head>
<body onload="Logon()">
</body>
</html>
Output:
28
Client-Side Scripting (Semester-V)
<html>
<bod>
<script>
var x = myFunction(4, 3);
function myFunction(a, b)
{
return a * b;
}
document.write(x);
</script>
</body>
</html>
Output:
12
2.4 String
A string value is chain of zero or more Unicode characters.
You use string data type to represent text in JavaScript.
The String object is used to storing and manipulating text. A string is
simply storing the series of characters.
There are 2 ways to create string in JavaScript
A) By string literal:
Syntax:
var stringname=new String("string literal");
29
Client-Side Scripting (Semester-V)
In JavaScript there are various properties and methods associated with string
objects.
String Properties:
<html>
<head>
<title>JavaScript String constructor Method</title>
</head>
<body>
<script type = "text/javascript">
var str = new String();
document.write("str.constructor is:" + str.constructor);
</script>
</body>
</html>
Output:
30
Client-Side Scripting (Semester-V)
<html>
<body>
<h1>without using prototype property</h1>
<script>
function Student()
{
this.name = 'Pallavi';
this.gender = 'F';
}
<html>
<body>
<h1>Prototype</h1>
<script>
function Student()
{
31
Client-Side Scripting (Semester-V)
this.name = 'Pallavi';
this.gender = 'M';
}
Student.prototype.age = 20;
var studObj1 = new Student();
document.write(studObj1.age+"<br>");
var studObj2 = new Student();
document.write(studObj2.age);
</script>
</body>
</html>
Output:
String Methods:
Methods Description
charAt() It provides the char value present at the specified index
charCodeAt() It provides the Unicode value of a character present at
the specified index.
concat() It provides a combination of two or more strings.
indexOf() It provides the position of a char value present in the
given string.
lastIndexOf() It provides the position of a char value present in the
given string by searching a character from the last
position.
search() It searches a specified regular expression in a given
string and returns its position if a match occurs.
match() It searches a specified regular expression in a given
string and returns that regular expression if a match
occurs.
replace() It replaces a given string with the specified replacement.
32
Client-Side Scripting (Semester-V)
When you concatenate a string, you form a new string from two strings
by placing a copy of the second string behind a copy of the first string.
The new string contains all the characters from both the first and
second strings.
You use the concatenation operator (+) to concatenate two strings, as
shown here
<html>
<bod>
<script>
var s1="Rahul";
var s2="Patil";
var s3=s1.concat(s2);
document.write(s3);
var s4=s1+s2;
33
Client-Side Scripting (Semester-V)
document.write("<br>"+s4);
</script>
</body>
</html>
Output:
RahulPatil
RahulPatil
Output:
<html>
<body>
<script>
var s1="JavaScript is a scripting language";
var n=s1.indexOf("a");
34
Client-Side Scripting (Semester-V)
document.writeln(n+"<br>");
document.writeln(s1.search("scripting"));
var m=s1.lastIndexOf("a");
document.writeln("<br>"+m);
</script>
</body>
</html>
Output:
1
16
31
The split() method creates a new array and then copies portions of the
string, called a substring, into its array elements.
You must tell the split() method what string (delimiter) is used to
separate substrings in the string.
You do this by passing the string as an argument to the split() method.
<html>
<body>
<script>
var str="CO IF EJ";
document.write(str.split(" "));
</script>
</body>
</html>
Output:
CO,IF,EJ
35
Client-Side Scripting (Semester-V)
However, the split() method isn’t of much use to you if you need to
copy one substring.
For this, you’ll need to use one of two other methods: substring() and
substr().
2. In the real world, you probably won’t know the starting position and end
position of characters for your substring, because a user can enter any
length string into your application. You can overcome this problem by using
the substr() method The substr() method returns a substring. You must tell it
the starting position of
the first character that you want to include in the substring and how many
characters you want copied into the substring from the starting position.
Both positions are passed as arguments to the substr() method.
Syntax:
String.substr(startindex,length);
<html>
<body>
<script>
var str="JavaScript";
document.write(str.substr(0,6));
document.write("<br>");
document.writeln(str.substring(4,9));
</script>
</body>
</html>
Output:
JavaSc
Scrip
36
Client-Side Scripting (Semester-V)
<html>
<body>
<script>
var a=50;
var b="67";
var c="45.75";
var ans=a + parseInt(b)+parseFloat(c);
document.write("Addition="+ans);
var sum=a+ Number(b)+parseFloat(c);
document.write("<br>"+"SUM="+sum);
</script>
</body>
</html>
Output:
Addition=162.75
SUM=162.75
37
Client-Side Scripting (Semester-V)
<html>
<body>
<script>
var a=50;
var b=80;
var ans=a + b.toString();
document.write("Addition="+ans);
</script>
</body>
</html>
Output:
Addition=5080
<html>
<body>
<script>
var str = "JavaScript";
document.writeln(str.toLowerCase());
document.writeln("<br>"+str.toUpperCase());
</script>
</body>
</html>
Output:
38
Client-Side Scripting (Semester-V)
javascript
JAVASCRIPT
<html>
<body>
<script>
var x="Javatpoint";
document.writeln(x.charCodeAt(3));
document.write("<br>");
var res = String.fromCharCode(72, 69, 76, 76, 79);
var res1 = String.fromCharCode(73, 70, 77, 77, 80);
document.write(res);
document.write("<br>"+res1);
</script>
</body>
</html>
Output:
97
HELLO
IFMMP
39
Client-Side Scripting (Semester-V)
Code:charCodeAt()
<script>
var x="Javatpoint";
document.writeln(x.charCodeAt(3));
</script>
Output:
97
<script>
var str="JavaProgramming";
document.writeln(str.replace("Programming","Script"));
</script>
Output:
JavaScript
The search() method searches a string for a specified value, and returns the
position of the match.
Syntax: string.search(searchvalue);
<script>
var str="JavaScript is a scripting language.";
document.writeln(str.search("scripting"));
</script>
Output:
16
40
Client-Side Scripting (Semester-V)
<script>
var str="JavaProgramming";
document.writeln(str.match("Java"));
</script>
Output:
Java
The slice() method returns the selected elements in an array, as a new array
object.
The slice() method selects the elements starting at the given start argument,
and ends at, but does not include, the given end argument
Where,
Start: Optional. An integer that specifies where to start the selection (The
first element has an index of 0). Use negative numbers to select from the
end of an array. If omitted, it acts like "0"
Code:
41
Client-Side Scripting (Semester-V)
<script>
var str = "JavaScript";
document.writeln(str.slice(0));
document.writeln("<br>"+str.slice(4));
</script>
Output:
JavaScript
Script
<html>
<body>
<button onclick = "myfunction()">click</button>
<script language="javascript" type="text/javascript">
function myfunction()
{
var s1 = "client scripting";
var s2 = " side";
var output = [s1.slice(0, 6), s2, s1.slice(6)].join('');
document.write(output);
}
</script>
</body>
</html>
Output:
https://forms.office.com/Pages/DesignPage.aspx?
origin=shell#FormId=QEUap70T20yz690UXwrJwIuVSIKHZ3RDo4EeJ2CYjgFUM004N1M1WEUwT0laVTZB
M0xLREdXWVVaMy4u
42