Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

Chapter 2 Array Function String

Uploaded by

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

Chapter 2 Array Function String

Uploaded by

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

Chapter 2

Array, Functions and String

Subject – Client Side Scripting Language(CSS-22519)


Class :If5I
Mrs. Alinka Sachin Shinde
Government Polytechnic Solapur
Information Technology Department
Arrays
 Information is stored into memory by assigning the information to a variable.
 Suppose you have to store 100 pieces of information in memory, such as the
name of 100 products in a sales catalog. You could declare 100 variables to store
product names; this might seem a good idea until you realized that you’d have to
devise 100 unique variable names and then name all the variables every time
your JavaScript needed to process the list of product names.
 Professional JavaScript developers use an array instead of a long list of variables.
 An array has one name and can hold as many values as is required by your
JavaScript application.
What Is an Array?
 An array is a special variable, which can hold more than one value at a time.
 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 identifies an array element.
 The combination of the array name and an index is nearly the same as a variable
name.
Declaring an Array
 There are basically two ways to declare an array.
➢ Method 1 : JavaScript Array directly (new keyword)
var arrayname = new Array()
var product = new Array()
➢ Method 2 : JavaScript array literal
var arrayname=[ ];
var emp=[ ]
Initializing an Array
 Initialization is the process of assigning a value when either a variable
or an array.
 When initializing an array, you place the value within the parentheses of
the Array() constructor
var name = new Array(‘Alinka’)
 To initialize the array with more than one value.
 Method 1
var name = new Array(‘Alinka', ‘Radha', ‘Ganesh', ‘Mohan’)
 Method 2
var name = [‘Alinka', ‘Radha', ‘Ganesh', ‘Mohan’]
Defining Array Elements/Assigning
Array Elements

 An array as a list containing some kind of information.


 Each item on the list is identified by the number in which the item
appears on the list. The first item is number 0, the second item is
number 1, then 2, and so on.
 To assign a product name to an array element, you must specify the
name of the array followed by the index of the array element. The
index must be enclosed within square brackets.
Example
var product = [ ]
product[0]=‘Soda’
product[1]=‘Water’
product[2]=‘Maza’
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 = product.length
 It is important to remember that the length of an array is the actual
number of array elements and not the index of the last array
element.
Looping the Array
 when you need to process each element of the array. You can use a for loop to access each array
element.
<html>
<body>
<script>
var emp=['Sonu','Vimal','Ratan'];
for (i=0;i<emp.length;i++)
{
document.write(emp[i] + "<br/>");
}
</script>
</body>
</html>
Script for finding length of Array
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>The length property returns the length of an array.</p>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.length;
</script>
</body>
</html>
:

Adding an Array Element


You can use the array's length property to add an element to the end of the array.
var arr = ['one', 'two', 'three’];
arr[arr.length]=‘Four’;
document.write(arr);
Output: [one,two,three,Four]
Array Methods

✓ push() : adds a one or more new elements to an array (at the end):
Syntax
Array.push(item1, item2 …)
Example:
var a=[10,20,30,40]
a.push(50)
a.push(60,70,80)
document.write(a)
output:
[10,20,30,40,50,60,70,80]
Array Methods

✓ unhift() : adds a one or more new elements to an array (at the


beginning):
Syntax
Array.unshift(item1, item2 …)
Example:
var a=[10,20,30,40]
a.unshift(60,70,80)
document.write(a)
output:
[60,70,80 ,10,20,30,40]
Array Methods
✓ pop() :Removing elements from the end of an array :
Syntax
Array.pop()
Example:
var a=[10,20,30,40]
a.pop()
document.write(a)
output:
[10,20,30]
Array Methods
✓ shift() : Removing elements at the beginning of an array :
Syntax
Array.shift()
Example:
var a=[10,20,30,40]
a.shift()
document.write(a)
output:
[20,30,40]
Array Methods

✓ splice() : Insertion and Removal in between an Array :


Syntax
Array.splice (start, deleteCount, item 1, item 2….)
Parameters:
Start : Location at which to perform operation
deleteCount: Number of element to be deleted, if no element is to be deleted pass 0.
Item1, item2 …..- this is an optional parameter. These are the elements to be inserted from location
start

var arr = [ 20, 30, 40, 50, 60 ];


arr.splice(1, 3);
// splice() deletes 3 elements starting from 1 number array contains [20, 60]
arr.splice(1, 0, 3, 4, 5);
// doesn't delete but inserts 3, 4, 5 at starting location 1 array contains [20,3,4,5,30,40,50,60]
✓ sort() :The sort() method sorts the items of an array.The sort order can be either alphabetic or
numeric, and either ascending (up) or descending (down).
var ar = [37, 18, 22, 8, 4];
ar.sort();
document.write( ar); // [ 4,8,18,22,37]
Making a New Array from an Existing Array
 The slice() method copies a sequential number of array elements from one array into a new
array. This means values of these elements exist in both arrays.
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var f = fruits.slice(1, 3);
Output: Orange,Lemon
Combining Array Elements into a String

 Array elements can be combined in two ways: by using the concat() method
or the join() method of the array object
 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
 Here’s how to use the concat() method:
var str = products.concat()
The value of str is
'Soda,Water,Pizza,Beer'
 Here’s how to use the join() method. In this example, we use a space to separate values:
var str = products.join(' ‘)
The value of str in this case is
'Soda Water Pizza Beer'
The reverse() method reverses the order of
the elements in an array.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.reverse();
Output : Mango,Apple,Orange,Banana
Function
Function
✓ A JavaScript function is a block of code designed to perform a particular
task.
✓ 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.
✓ Two kinds of functions are used in JavaScript:
1.predefined functions
2.custom functions
✓ A predefined function is already created for you in JavaScript, such as the
alert() function.
✓ A custom function is a function that you create.
Custom function

function DisplayHelloWorld()
{
alert('Hello, world!')
}

✓ The process of creating a function is called defining a function.

✓ The process of using the function is referred to as calling a


function.
Defining a Function
 A function must be defined before it can be called in a
JavaScript statement.
 The place to define a function is at the beginning of a JavaScript
that is inserted in the <head> tag.The browser always loads
everything in the <head> tag before it starts executing any
JavaScript.
 A function definition consists of four parts:
1.name
2.parentheses
3.code block
4.An optional return keyword
1. 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.
✓ The name must be
• Letter(s), digit(s), or underscore character
• Unique to JavaScripts, as no two functions can have the same name
✓ The name cannot
• Begin with a digit
• Be a keyword
• Be a reserved word
✓ The name should be
• Representative of the action taken by statements within the function
2.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.

3.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. Statements that you want executed must appear between the
open and close braces.

4.Return (Optional)
 The return keyword tells the browser to return a value from the function definition to the
statement that called the function.
Writing a Function Definition
 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 name(parameter1, parameter2, parameter3)
{
// code to be executed
}
 Example:
function sayHello()
{
document.write ("Hello there!");
}
Calling a Function

 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.
sayHello()
Example 1
<html>
<head>
<script type = "text/javascript">
function sayHello()
{
document.write ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello()" value = “Click Me">
</form>
</body>
</html>
Adding Arguments
 Sometimes you provide the data when you define the function.
 Data that is needed by a function to perform its task that is not written into the
function definition must be passed to the function as an argument.
 An argument is one or more variables that are declared within the parentheses
of a function definition.
 You can create functions with arguments as well. Arguments should be specified
within parenthesis.
function functionname(arg1, arg2)
{
lines of code to be executed
}
Write a JavaScript function to count the number of vowels in a given string
<html>
<head>
<script type="text/javascript">
var count = 0;
function countVowels(name)
{
for (var i=0;i<name.length;i++)
{
if(name[i] == "a" || name[i] == "e" || name[i] == "i" || name[i] == "o" || name[i] == "u")
count = count + 1;
}
document.write("Hello " + name + "!!! Your name has " + count + " vowels.");
}
var myName = prompt("Please enter your name");
countVowels(myName);
</script>
</head>
<body></body></html>
Adding Multiple Arguments

function IncreaseSalary(Old, Per)


{
var New = Old * (1 + (Per / 100))
alert("Your new salary is " + New)
}
The Scope of Variables and Arguments
 A variable can be declared within a function, such as the
NewSalary variable in the IncreaseSalary() function. This is called a
local variable, because the variable is local to 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.
 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.
Calling a Function
✓ Calling a Function Without an Argument
function showMessage()
{
alert( 'Hello everyone!' );
}
showMessage();
✓ Calling a Function with an Argument
function say(message)
{
alert(message);
}
say(“Hello Good Atfernoon!!”);
Calling a Function from HTML

 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, button is clicked etc.
 In HTML code you assign the function call as a value of an HTML tag attribute.
Example
<html>
<head>
<script type = "text/javascript">
function myfunction()
{
alert("how are you");
}
</script>
<body>
<p>Click the following button to see the function in action</p>
<input type = "button" onclick = "myfunction()" value = "Display">
</body>
Returning values from function
Functions Calling Another Function
In JavaScript we can call one function inside another function.
<html>
<head><script>
function function_one()
{
alert(" function_one() has been called.");
function_two();
}
function function_two()
{
alert("function_two() has been called.");
}
function_one();
</script>
</head>
</html>
<html>
<head>
<script>
function accepts(name)
{
document.write(“Enter your city name = ”+name);
}
function display()
{
accepts(“Solapur”);
}
display();
</script>
</head>
</html>
Returning Values from a Function

✓ A function reports back to the statement that calls the function by returning a
value to that statement using the return keyword, followed by a return value in a
statement.
Here’s what this looks like:
function name ()
{
return value
function add(a, b)
} function square(x) {
{ return a + b;
return x * x; }
}
var sum = add(5, 24);
var demo = square(3);
<html>
<head>
<script>
function concatenate(name, age)
{
var val;
val = name + age;
return val;
}
function DisplayFunction()
{
var result;
result = concatenate(‘Ganesh', 20) ;
document.write (result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "DisplayFunction()" value = "Result">
</form> </body> </html>
Validation of user id and password by returning values

<html>
<head>
<title>Returning a value from a function</title>
<script language="Javascript" type="text/javascript">
function Logon()
{
var userID, password, 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 ReturnValue
if (id == 'Alinka' && pwd == 'Alinka123')
{
ReturnValue = true
}
else
{
ReturnValue = false
}
return ReturnValue
}
</script>
</head>
<body>
<p>Click the following button validate Login Details</p>
<form>
<input type = "button" onclick = "Logon()" value = "Validate
Login">
</form>

</body>
</html>
STRING
16/9/2020
STRING
➢ A string is text that is enclosed within quotation marks. It is called a string because
characters are put together to form the text.
➢ The JavaScript string is an object that represents a sequence of characters.
➢ There are 2 ways to create string in JavaScript
1. By string literal

var stringname="string value";


var s=“Government Polytechnic Solapur”
2.By string object (using new keyword)
var stringname=new String("string value");

var stringname=new String(" Government Polytechnic Solapur ");


JAVASCRIPT STRING METHODS
• charAt() :
✓ The JavaScript string charAt() method is used to find out a char value present at the
specified index in a string.
✓ The index number starts from 0 and goes to n-1, where n is the length of the string. The
index value can't be a negative, greater than or equal to the length of the string.
String.charAt(index)

var str="JavaScript";
document.write(str.charAt(4));
• concat() :
✓ The JavaScript string concat() method combines two or more strings and returns a new
string .
string.concat(str1,str2,...,strn)

var x="JavaScript";
var y=“ is a Client Side Scripting Language";
document.writeln(x.concat(y));
• indexOf():
• The JavaScript string indexOf() method is used to search the position of a particular
character or string in a sequence of given char values. The index position of first
character in a string is always starts with zero. If an element is not present in a string, it
returns -1.
var str="Learn JavaScript ";
document.write(str.indexOf('a'));

• lastIndexOf()
• The JavaScript string lastIndexOf() method is used to search the position of a particular
character or string in a sequence of given char values. It behaves similar to indexOf()
method with a difference that it start searching an element from the last position of the
string.
var str="Learn JavaScript";
document.write(str.lastIn dexOf('a'));
• replace()
• The JavaScript string replace() method is used to replace a part of a given string with a new
substring. This method searches for specified regular expression in a given string and then replace
it if the match occurs.
string.replace(originalstr,newstr)
var str=“I m Pass";
document.write(str.replace(“Pass",“Fail"));
• substr()
• The JavaScript string substr() method fetch the part of the given string and return the new string.
string.substr(start,length)
var str="JavatScript";
document.write(str.substr(0,4));
• substring()
• The JavaScript string substring() method fetch the string on the basis of provided
index and returns the new sub string.
string.substring(start,end)
var str="JavaScript";
document.writeln(str.substri
ng(4,5));

• slice()
• The JavaScript string slice() method is used to fetch the part of the string and returns
the new string. It required to specify the index number as the start and end
parameters to fetch the part of the string. The index starts from 0.
string.slice(start,end)
var str = "Javatpoint";
document.writeln(str.slice(2,5));
• toLowerCase()
• The JavaScript string toLowerCase() method is used to convert the string into lowercase
letter.This method doesn't make any change in the original string.
string.toLowerCase()
var str = "JAVASCRIPT tutorials";
document.writeln(str.toLowerCase());
• toUpperCase()
• The JavaScript string toUpperCase() method is used to convert the string into uppercase
letter.
string.toUpperCase()
var str = "javascript";
document.writeln(str.toUpperCase());
• toString():
• This method returns a string representing the specified object.
string.toString( )
var str = "Apples are round, and Apples are Juicy.";
document.write(str.toString( ));

• split()
• This method splits a String object into an array of strings by separating the string into substrings.
string.split([separator][, limit]);
separator − Specifies the character to use for separating the string.
limit − Integer specifying a limit on the number of splits to be found.
var str = "Apples are round, and apples are juicy.";
var splitted = str.split(" ", 3);
document.write( splitted );
Converting Numbers and Strings
• We know that a number and a string are two different types of data in JavaScript. A
number is a value that can be used in a calculation; a string is text and can include
numbers, but those numbers cannot be used in calculations.

• The parseInt( ) method converts a number in a string to an integer numeric value,


which is a whole number.You write the parseInt( ) method this way:
var StrCount = '100’
var num = parseInt(StrCount)
• Here’s how to use the parseFloat( ) method:
var StrPrice = '10.95’
var NumPrice = parseFloat(StrCount)
Strings and Unicode
• we know that a computer understands only numbers and not characters.when you enter a character,
such as the letter w, the character is automatically converted to a number called a Unicode number
that your computer canunderstand.
• Unicode is a standard that assigns a number to character, number, and symbol that can be displayed
on a computer screen, including characters and symbols that are used in all languages.
• You can determine the Unicode number or the character that is associated with a Unicode number
by using the charCodeAt( ) method and fromCharCode( ) method.
• Both are string object methods. The charCodeAt( ) method takes an integer as an argument that
represents the index of the character in which you’re interested. If you don’t pass an argument, it
defaults to index 0.

• The charCodeAt( ) method returns the Unicode number of the string:

• var UnicodeNum = StringName.charCodeAt( )


• Here’s how to determine the Unicode number of the letter w:

• var Letter = 'w'

• var UnicodeNum = Letter.charCodeAt( )

• The Letter.charCodeAt( ) method returns the number 119, which is the Unicode
number that is assigned the letter w. Uppercase and lowercase versions of each
letter have a unique Unicode number.

• If you need to know the character, number, or symbol that is assigned to a


Unicode number, use the fromCharCode( ) method. The fromCharCode( )
method requires one argument, which is the Unicode number. Here’s how to use
the fromCharCode( ) method to return the letter w.

• var Letter = String.fromCharCode(119)

You might also like