0% found this document useful (0 votes)
60 views

Chapter 2 CSS

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views

Chapter 2 CSS

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Client-Side Scripting Language (CSS)-22519

Chapter 2

2.1 Array - declaring an Array, Initializing an Array, defining an Array elements,


Looping an Array, Adding an Array element, sorting an Array element, Combining
an Array elements into a String, changing elements of an Array, Objects as
associative Arrays
2.2 Function - defining a function, writing a function, adding an arguments, scope of
variable and arguments,
2.3 Calling a function – calling a function with or without an argument, calling
function from HTML, function calling another function. Returning value from a
function
2.4 String -- manipulate a sting, joining and string, retrieving a character from given
position, retrieving a position of character in a string, dividing text, copying a sub
string, converting string to number and numbers to string, changing the case of string,
finding a Unicode of a character-charCodeAt(), fromCharCode().

Array:
An array is very similar to a variable in that an array tells the browser to reserve
a place in memory that can be used to store information. An array can comprise one
or multiple elements. Each element is like a variable in that an array element refers
to a memory location where information can be temporarily stored. An array is
identified by a unique name, similar to the name of a variable. A number called an
index identifi es an array element. The combination of the array name and an index
is nearly the same as a variable name. JavaScript array is an object that represents a
collection of similar type of elements.

Declaring an Array
There are 3 ways to construct array in JavaScript

1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)

1) JavaScript array literal


The syntax of creating array using array literal is given below:
var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by , (comma)

Mrs. Shubhangi Chintawar 1


Client-Side Scripting Language (CSS)-22519

<html>
<body>
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
</body>
</html>

o/p
Sonoo
Vimal
Ratan

How Many Elements Are in the Array?


The length property of the array object contains the number of elements contained
in the array.
var len = products.length
You specify the name of the array object (products) and the name of the property
(length), separated by a dot

2)JavaScript Array directly (new keyword)


The syntax of creating array directly is given below:

var arrayname=new Array();


Here, new keyword is used to create instance of array.

<html>
<body>
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";

Mrs. Shubhangi Chintawar 2


Client-Side Scripting Language (CSS)-22519

emp[2] = "John";

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

Example 2)
<html>
<head>
<title>Display Array Elements</title>
</head>
<body>
<script language="Javascript" type="text/javascript">
var products = new Array()
products[0] = 'Soda '
products[1] = 'Water'
products[2] = 'Pizza'
products[3] = 'Beer'
for (var i = 0; i < products.length; i++)
{
document.write(products[i] + '<br>')
}
</script>
<noscript>
<h1> JavaScript Required</h2>
</noscript>
</body>
</html>

3) JavaScript array constructor (new keyword)


you need to create instance of array by passing arguments in constructor so that we
don't have to provide value explicitly.

The example of creating object by array constructor is given below.


<html>

Mrs. Shubhangi Chintawar 3


Client-Side Scripting Language (CSS)-22519

<body>
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>

Adding an Array Element


in some situation , JavaScript will need to increase the size of the array while
your JavaScript is running. This means that your JavaScript must be
prepared to increase the array by one element each time the customer enters a new
product.
To know what index to assign to the new array element. The solution is to use the
length property of the array, as illustrated here:
products[products.length] = 'chips’;

Example:

<html>
<head>
<title>Display Array Elements</title>
</head>
<body>
<script language="Javascript">
var products = new Array()
products[0] = 'Soda ';
products[1] = 'Water';
products[2] = 'Pizza';
products[3] = 'Beer';
products[products.length] = 'chip';
for (var i = 0; i < products.length; i++)
{
document.write(products[i] + '<br>');
}

Mrs. Shubhangi Chintawar 4


Client-Side Scripting Language (CSS)-22519

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

Sorting Array Elements


3. sort() method: t returns the element of the given array in a sorted order.

<html>
<head>
<title>Display Array Elements</title>
</head>
<body>
<script language="Javascript">
var products = new Array()
products[0] = 'Soda ';
products[1] = 'Water';
products[2] = 'Pizza';
products[3] = 'Beer';
products.sort();
for (var i = 0; i < products.length; i++)
{
document.write(products[i] + '<br>');
}
</script>
</body>
</html>

o/p
Beer
Pizza
Soda
Water

Combining Array Elements into a String

concat():It returns a new array object that contains two or more merged arrays.
The concat() method separates each value with a comma.

Mrs. Shubhangi Chintawar 5


Client-Side Scripting Language (CSS)-22519

join():It joins the elements of an array as a string.The


join() method also uses a comma to separate values, but you can specify a character
other than a comma to separate values. we can perform this by placing that character
in the parentheses of the join() method.
we can change the value in the join() method to any
character that you want the browser to use to separate these values.

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array Methods</h2>
<h2>concat()</h2>
<p>The concat() method is used to merge (concatenate) arrays:</p>
<script>
var myGirls = ["Cecilie", "Lone"];
var myBoys = ["Emil", "Tobias", "Linus"];
var myChildren = myGirls.concat(myBoys);
document.write(myChildren);
</script>

</body>
</html>
o/p

JavaScript Array Methods


concat()
The concat() method is used to merge (concatenate) arrays:

Cecilie,Lone,Emil,Tobias,Linus

2)<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array Methods</h2>
<h2>join()</h2>
<script>
var myGirls = ["Cecilie", "Lone"];
var myBoys = ["Emil", "Tobias", "Linus"];

Mrs. Shubhangi Chintawar 6


Client-Side Scripting Language (CSS)-22519

var myChildren = myGirls.join(myBoys);


document.write(myChildren);
</script>
</body>
</html>

o/p
JavaScript Array Methods
concat()
The concat() method is used to merge (concatenate) arrays:
CecilieEmil,Tobias,LinusLone

3)
<html>
<head>
<title>Display Array Elements Using concat() and join()</title>
</head>
<body>
<script language="Javascript">
var products = new Array();
products[0] = 'Soda' ;
products[1] = 'Water';
products[2] = 'Pizza';
products[3] = 'Beer';
var str = products.concat();
document.write(str);
document.write('<br>');
var str = products.join(' ');
document.write(str);
</script>
<noscript>
<h1> JavaScript Required</h2>
</noscript>
</body>
</html>

o/p
Soda,Water,Pizza,Beer

Mrs. Shubhangi Chintawar 7


Client-Side Scripting Language (CSS)-22519

Soda Water Pizza Beer

Changing Elements of the Array

Methods Description
concat()
It returns a new array object that contains two or more merged arrays.
copywithin()
It copies the part of the given array with its own elements and returns the modified
array.
every()
It determines whether all the elements of an array are satisfying the provided function
conditions.
fill()
It fills elements into an array with static values.
filter()
It returns the new array containing the elements that pass the provided function
conditions.
find()
It returns the value of the first element in the given array that satisfies the specified
condition.
findIndex()
It returns the index value of the first element in the given array that satisfies the
specified condition.
forEach()
It invokes the provided function once for each element of an array.
includes()
It checks whether the given array contains the specified element.
indexOf()
It searches the specified element in the given array and returns the index of the first
match.
join()
It joins the elements of an array as a string.
lastIndexOf()
It searches the specified element in the given array and returns the index of the last
match.
map()
It calls the specified function for every array element and returns the new array

Mrs. Shubhangi Chintawar 8


Client-Side Scripting Language (CSS)-22519

pop()
It removes and returns the last element of an array.
push()
It adds one or more elements to the end of an array.
reverse()
It reverses the elements of given array.
shift()
It removes and returns the first element of an array.
slice()
It returns a new array containing the copy of the part of the given array.
sort()
It returns the element of the given array in a sorted order.
splice()
It add/remove elements to/from the given array.
unshift()
It adds one or more elements in the beginning of the given array.

<html>
<head>
</head>
<body>
<script language="Javascript">
var products = new Array();
products[0] = 'Soda' ;
products[1] = 'Water';
products[2] = 'Pizza';
products[3] = 'Beer';
document.write("Original array<P>");
for (var i = 0; i < products.length; i++)
{ document.write(products[i] + '<br>');
}
products.pop();
document.write("<p>after pop() remove last element <BR>");
for (var i = 0; i < products.length; i++)
{ document.write(products[i] + '<br>');
}
products.push('Burger');

Mrs. Shubhangi Chintawar 9


Client-Side Scripting Language (CSS)-22519

document.write("<p>after push array add element at end <br>");


for (var i = 0; i < products.length; i++)
{ document.write(products[i] + '<br>');
}

document.write("<p>after reverse element of list<br>");


products.reverse();
for (var i = 0; i < products.length; i++)
{ document.write(products[i] + '<br>');
}
</script>
</body>
</html>

o/p
Original array
Soda
Water
Pizza
Beer
after pop() remove last element
Soda
Water
Pizza
after push array add element at end

Soda
Water
Pizza
Burger
after reverse element of list
Burger
Pizza
Water
Soda

Mrs. Shubhangi Chintawar 10


Client-Side Scripting Language (CSS)-22519

Function
Function as part of your JavaScript that has a name and contains one or more
statements they are used to perform operations. We give name to the function and
write the statement(s) that are con-tained within the function. We can use the name
of the function elsewhere in your JavaScript whenever you want the browser to
execute those statements. A function can be called from anywhere in the JavaScript
file or in the HTML document. JavaScript functions We can call JavaScript function
many times to reuse the code.

A function definition consists of four parts: the name, parentheses, a code block,
and an optional return keyword.

The function name must be:


• Letter, digit, or underscore character
• Unique to JavaScripts on your web page, as no two functions can have the
same name

Dont's:
• Cannot begin with a digit
• Cannot be a keyword
• Cannot be a reserved word

Syntax of function:
function function-name(){
//body of function;
}

example of function:
function IncreaseSalary()
{
var salary = 500000 * 1.25;
alert('Your new salary is ' + salary);
}

MULTIPLE ARGUMENTS:
example of function with arguments
function IncreaseSalary(OldSalary, PercIncrease)
{

Mrs. Shubhangi Chintawar 11


Client-Side Scripting Language (CSS)-22519

var NewSalary = OldSalary * (1 + (PercIncrease / 100))


alert("Your new salary is " + NewSalary)
}

SCOPE OF VARIABLES:

function IncreaseSalary(OldSalary)
{
var NewSalary = OldSalary * 1.25
alert("Your new salary is " + NewSalary)
}

From the above example,a variable can be declared within a function, such as the
OldSalary variable in the IncreaseSalary() function.Is called a local variables.

CALLING OF FUNCTION:
A function is called by using the functionname 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 defintion.

Syntax:
functionname();
Example of Calling a function without arguments:

IncreaseSalary();
Example of Calling a function with arguments:

IncreaseSalary(600000,9);

Advantage of JavaScript function


Code reusability: We can call a function several times so it save coding.
Less coding: It makes our program compact. We don’t need to write many lines of
code each time to perform a common task.

<html>
<head>
<title>Functions</title>

Mrs. Shubhangi Chintawar 12


Client-Side Scripting Language (CSS)-22519

<script language="Javascript">
function IncreaseSalary()
{
var salary = 500000 * 1.25
//alert('Your new salary is ' + salary)
document.write("new salary is "+salary);
}
</script>
</head>
<body>
<script language="Javascript">
IncreaseSalary();
</script>
</body>
</html>

With args
<html>
<head>
<title>Functions</title>
<script language="Javascript">
function IncreaseSalary(OldSalary, PercIncrease)
{
var NewSalary =OldSalary * (1 + (PercIncrease / 100));
alert("Your new salary is " + NewSalary);
}
</script>
</head>
<body>
<script language="Javascript">
var Salary = prompt('Enter old salary.', ' ');
var Increase =prompt('Enter salary increase as percent.', ' ');
IncreaseSalary(Salary, Increase);
</script>
</body>
</html>

Mrs. Shubhangi Chintawar 13


Client-Side Scripting Language (CSS)-22519

String
String is a collection of character. JavaScript strings are used for storing and
manipulating text.
There are 2 ways to create string in JavaScript
By string literal
By string object (using new keyword)

By string literal
The string literal is created using double quotes.
The syntax of creating string using string literal is given below:
var stringname="string value";

<html>
<body>
<script>
var str="This is string literal";
document.write(str);
</script>
</body>
</html>

By string object (using new keyword)


The syntax of creating string object using new keyword is given below:
var stringname=new String("string literal");

Here, new keyword is used to create instance of string.


<html>
<body>
<script>
var stringname=new String("hello javascript string");
document.write(stringname);
</script>
</body>
</html>

Mrs. Shubhangi Chintawar 14


Client-Side Scripting Language (CSS)-22519

String Methods

1. split()
2. substring()
3. substr()
4. tolowercase()
5. touppercase()
6. valueof()
7. tostring()
8. parseint()
9. parsefloat()

concat()
The JavaScript string concat() method combines two or more strings and returns a
new string. This method doesn't make any change in the original string.

Syntax:-
string.concat(str1,str2,...,strn)
str1,str2,...,strn - It represent the strings to be combined.

<html>
<body>
<script>
var x="CO";
var y="Class B";
var z=" VESP";
document.writeln(x.concat(y,z));
</script>
</body>
</html>

Mrs. Shubhangi Chintawar 15


Client-Side Scripting Language (CSS)-22519

Lower and upper Case string-


the toLowerCase() method to convert a
string to lowercase characters

the toUpperCase()
method, which converts a string to uppercase characters

<!DOCTYPE html>
<html>

<head>
<title>toString method</title>
</head>

<body>
<script type="text/javascript">
var a = "MSBTE";
var WebSite = prompt(a+" to lowercase.", a.toLowerCase());
var b = "vesp";
var WebSite = prompt(b+" to uppercase.", b.toUpperCase());
</script>
</body>

</html>

charAt()
The charAt() method requires one argument i.e is the index of the character that you
want to copy. The following statement illustrates how to use the charAt() method:

var SingleCharacter = NameOfStringObject.charAt(index);

html>
<head>
<title>Copy one character of a string</title>
</head>
<body>

Mrs. Shubhangi Chintawar 16


Client-Side Scripting Language (CSS)-22519

<script type="text/javascript">
var FirstName = 'Bob';
var Character = FirstName.charAt(0);
alert(Character);
</script>
</body>
</html>

indexOf()
the index of a character by calling the indexOf() method of the string object. The
indexOf() method returns the index of the character passed to it as an argument.
If the character is not in the string, the method returns –1.
var IndexValue = string.indexOf('character');

<html>
<head>
<title>Identifying the index of a character in a string</title>
</head>
<body>
<script type="text/javascript">
var FirstName = 'Bob';
var IndexValue = FirstName.indexOf('o');
alert(IndexValue);
if(IndexValue != -1)
{
var Character = FirstName.charAt(IndexValue);
alert(Character);
}
</script>
</body>
</html>

Split()

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

Mrs. Shubhangi Chintawar 17


Client-Side Scripting Language (CSS)-22519

string as an argument to the split() method. In this example, the comma is the string
that separates substrings. Here’s how you use the split() method:
var NewStringArray = StringName.split('delimiter string');

<!DOCTYPE html>
<html>

<head>
<title>Dividing a delimited string into a substring</title>
</head>
<body>
<script type="text/javascript">
var DataString = 'Bob Smith,Mary Jones,Tom Roberts,Sue Baker';
var NewArray = DataString.split(',');
document.write(DataString);
document.write('<br>');
for (i = 0; i < 4; i++) {
document.write(NewArray[i]);
document.write('<br>');
}
</script>
</body>

substring() :
The starting position specifies the first character that is returned by the substring()
method that is, the first character in the substring. The end position specifies the
character that follows the last character that is returned by the substring() method
that is, the position of the character that comes after the last character that you want
to include in the substring.
var NewSubstring = StringName.substring (StartingPosition, EndPosition);

<html>
<head>
<title>Using substring()</title>
</head>

<body>
<script type="text/javascript">

Mrs. Shubhangi Chintawar 18


Client-Side Scripting Language (CSS)-22519

var EmailAddress = '[email protected]';


var NewSubstring = EmailAddress.substring(7, 14);
var GuessWebSite = 'www.' + NewSubstring;
var WebSite = prompt('Enter the client web site.', GuessWebSite);
</script>
</body></html>

The parseInt() method converts a string to an integer numeric


value, which is a whole number. You write the parseInt() method this way:
var num = parseInt(StringName);

The parseFloat() method is used similarly to the parseInt() method,


except the parseFloat() method is used with any number that has a decimal
value.
var num = parseFloat(StringName);
<html>

<head>
<title>String to Integer and Float</title>
</head>
<body>
<script type="text/javascript">
var a = "123";
var WebSite = prompt("Integer value of String.", parseInt(a));
var b = "123.75";
var WebSite = prompt("Float value of String.", parseFloat(b));
</script>
</body>
</html>

The toString() method can be used to convert both integers and decimal values
(floats) into String. To convert a number value to a string:
Var NumCount = 100;
var StrCount = NumCount.toString();
<!DOCTYPE html>
<html>
<head>

Mrs. Shubhangi Chintawar 19


Client-Side Scripting Language (CSS)-22519

<title>toString method</title>
</head>
<body>
<script type="text/javascript">
var a = 123;
var WebSite = prompt("String value of Integer.", a.toString());
var b = 123.75;
var WebSite = prompt("String value of Float.", b.toString());
</script>
</body>
</html>

Mrs. Shubhangi Chintawar 20

You might also like