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

CSS Chapter 2Notes

Uploaded by

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

CSS Chapter 2Notes

Uploaded by

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

Unit II : Array, Function and String

Unit Outcomes(UOs)
2a. Create array to solve the given problem.
2b. Perform the specified string manipulation operation on the given String.
2c. Develop JavaScript to implement the given function.
2d. Develop JavaScript to convert the given function.
2e. Develop JavaScript to convert the given character to Unicode and Vice-Versa.

Contents
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 n Array element into a String, changing elements of an
Array, object as associative Array.
2.2 Function – Defining a function, writing a function, adding as 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 a value from a function.
2.4 String – manipulate a string, joining a string, retrieving a character from a given position of character in
a string, dividing text, coping a substring, converting, string to number and numbers to string, changing the
case of string, finding a Unicode of a character – charCodeAt(), fromCharCode()

2 Marks Questions

1. Differentiate between shift() and push() methods of an Array object.

2. State the meaning of "Defining a function". Explain with the help of an example.
• A function is a block of code that takes some input to perform some certain computation.
• The main purpose of the function is to put commonly used or repeatedly used task in a function, so
instead of writing the code again and again we can call it instead.
• The function can be defined as followed:

Syntax:
function func_name(parameter1 ,parameter2,…,parametern)
{
//code
}
Example:
<script>
function add(num1,num2)
{
return num1 + num2;
}
add(1,2);
</script>

OR
3. Give syntax of and explain function in JavaScript with suitable example
Function is a collection of one or more statements written to execute a specific task.
Syntax to define a function:
function function_name([Arguments])
{
Statement block;
[return statement;]
}
Example:
function display ( )
{
alert (―WELCOME TO JAVASCRIPT‖);
}

4. Write a JavaScript that initialize an array called flowers with the names of 3 flowers. The script
then display array elements.
<html>
<head>
<title>Display Array Elements</title>
</head>
<body>
<script>
var flowers = new Array();
flowers[0] = 'Rose ';
flowers[1] = 'Mogra';
flowers[2] = 'Hibiscus';
for (var i = 0; i < flowers.length; i++)
{
document.write(flowers[i] + '<br>');
}
</script>
</body>
</html>

5. Write a javascript to call the function from html


<html>
<head>
<title>Calling function from HTML</title>
<script>
function welcome()
{
alert("Welcome students");
}
function goodbye()
{
alert("Bye");
}
</script>
</head>
<body onload="welcome()" onunload="goodbye()">
</body>
</html>

6. Explain scope of variable declared in function with example.


<html>
<body>
<form name="login">
Enter Username<input type="text" name="userid"><br>
Enter Password<input type="password" name="pswrd">
<input type="button" onclick="display()" value="Display">
</form>
<script language="javascript">
function display()
{
document.write("User ID "+ login.userid.value + "Password
:"+login.pswrd.value);
}
</script>
</body>
</html>

7. Write a program to Accept the marks of 10 subjects from the user and store it in array. Sort them
and display
<html>
<body>
<h2>Accept and Display the marks</h2>
<script>
a = new Array();
length=prompt("For how many subjects do you want to enter a
marks?");
alert("Enter Marks of Subjects")
for(i=0;i<length;i++)
{
a[i]=prompt("Enter marks of subject"+i);
}
document.write("<br/><br/>The entered subjects marks are<br\>");
for(i=0;i<length;i++)
{
document.write("Marks of subject"+i+"is :"+a[i]);
document.write("</br>");
}
document.write("<br/><br/>The array sorted subjects mareks
are<br\>");
a.sort();
document.write("<br/>The element in the array are<br\>");
for(i=0;i<length;i++)
{
document.write("Marks of subject"+i+"is :"+a[i]);
document.write("</br>"); }
</script>
</body>

8. Explain scope of variable declared in function with example.


Scope is the block or area of program in which particular variable or argument is possible
The scope of variable is defined using two types of variables – Local scope and Global scope
Local scope :
a. if a variable is defined inside a function then that variable is a local variable and its scope is a
local scope
b. 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.
Global variable :
a.A variable is called global variable, if it is defined outside t he function.
b. The variable having global scope is accessible by any function.

9. Write a JavaScript code to implement push() method of array.


<html>
<body>
<h2>Changing Array Demo</h2>
<script>
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 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>

10. Write a JavaScript code to implement concat() method of string.


<html>
<body>
<h2>Combining Array Demo</h2>
<script>
a = new Array();
a[0]="Red";
a[1]="Orange";
a[2]="Yellow";
a[3]="Green";
a[4]="Blue";
a[5]="Indigo";
a[4]="Voilet";
document.write("<h3>The concat() method</h3>")
var str2=a.concat();
document.write(str2);
</script>
</body>
</html>

11. Write the use of charAt() method and indexOf() method with syntax and example.
charAt()
• The charAt() method requires one argument i.e is the index of the character thatyou want
to copy.

Syntax:
var SingleCharacter = NameOfStringObject.charAt(index);

Example:
var FirstName = 'Bob';
var Character = FirstName.charAt(0); //o/p B

indexOf()
• The indexOf() method returns the index of the character passed to it as an
argument. If the character is not in the string, this method returns –1.

Syntax:
var indexValue = string.indexOf('character');

Example:
var FirstName = 'Bob';
var IndexValue = FirstName.indexOf('o'); //o/p index as 1

12. Difference between concat() and join() method of array with example.
concat() join()

Array elements can be combined byusing Array elements can be combined byusing join()
concat() method of Array object. method of Array object.
The concat() method separates eachvalue The join() method also uses a commato
with a comma. separate values, but you can specify a character
other than a comma to separate values.
Eg: Eg:
var str = cars.concat() var str = cars.join(' ')
The value of str is The value of str in this case is
'BMW, Audi, Maruti' 'BMW Audi Maruti'

13. Write a JavaScript code to display 5 elements of array in sorted order.


<html>
<body>
<h2>Sorting an Array element</h2>
<script>
a = new Array();
a[0]=10;
a[1]=50;
a[2]=40;
a[3]=20;
a[4]=30;
document.write("The elemnts in the array are<br/>")
for(i=0;i<a.length;i++)
{
document.write(a[i]+" ");
}
document.write("<br/><br/>The array is sorted<br\>");
a.sort();
document.write("<br/>The element in the array are<br\>");
for(i=0;i<a.length;i++)
{
document.write(a[i]+" ");
}
</script>
</body>
</html>

14. Write a JavaScript that will replace following specified value with another value in the string
String=”I will fail” replace “fail” by “pass”.
<html>
<head>
<body>
<script>
var myStr = ‘I will fail’;
var newStr = myStr.replace(fail, "pass");
document.write(newStr);
</script>
</body>
</head>
</html>
4 Marks Questions
15. Differentiate between substring() and substr() method of a string class. Give Suitable example of
each.
Example:
<script>
var a="Javascript";
document.write("Using substring()="+a.substring(2,6));
document.write("<br>Using substr()="+a.substr(2,6));
</script>
Output:
Using substring()=vasc
Using substr()=vascri

16. State the use of following methods:


i) charCodeAt( )
ii) fromCharCode ( )

1. charCodeAt( ): This method is used to return a unicode of specified character.

Syntax: var code=letter.charCodeAt( );


Example: var ch=‘a‘;
document.write(ch.charCodeAt( ));
Output: 97

2. fromCharCode( ): This method is used to return a character for specified code.

Syntax: var character=String.fromCharCode(code);


Example: var character=String.fromCharCode(97);
Document.write(ch);
Output: a

17.Explain Associative arrays in detail.


Associative arrays are basically objects in JavaScript where indexes are replaced by user-defined
keys.
Syntax:
var arr = {key1:'value1', key2:'value2'}
Here, arr, is an associative array with key1, key2 being its keys or string indexes and value1 & value
2 are its elements.
Example:
var arr = { "Company Name": ‗Flexiple‘, "ID": 123};
The content or values of associative arrays is accessed by keys. An associative array is an array with
string keys rather than numeric keys.
For example:
var arrAssociative = {
"Company Name": 'Flexiple',
"ID": 123
};
var arrNormal = ["Flexiple", 123];
Here, the keys of the associaKve array are ―Company Name‖ & ―ID‖
whereas in the normal array. The keys or index is 0 & 1.

18. Write a JavaScript function that checks whether a passed string is palindrome or not.
function isPalindrome(str) {
str = str.replace(/[^A-Za-z0-9]/g, '').toLowerCase();
return str === str.split('').reverse().join('');
}
console.log(isPalindrome("A man, a plan, a canal, Panama")); //
Output: true
console.log(isPalindrome("racecar")); // Output: true
console.log(isPalindrome("hello")); // Output: false

16. Write a JavaScript to check whether a passed string is palindrome or not


<html>
<body>
<h1>Palindrome</h1>
Enter String: <input type="text" id="txt" />
<input type="button" value="Check" onClick=checkPalindrome()/>
<p id="result"></p>
<script>
function checkPalindrome() {
var str = document.getElementById('txt').value;
const len = str.length;
var flag = 1;
for (var i = 0; i < len / 2; i++) {
if (str[i] !== str[len - 1 - i]) {
flag = 0;
}
}
if (flag == 1) {
document.getElementById("result").innerHTML = "It is a
palindrome";
}
else {
document.getElementById("result").innerHTML = "It is not a
palindrome";
}
}
</script>
</body>
</html>

17. Explain how to add and sort elements in array with suitable example.
Adding Elements to an Array:
In JavaScript, you can add elements to an array using various methods, such as push(), unshift(), or
direct assignment to a specific index.
Using push():
The push() method adds one or more elements to the end of an array and returns the new length of
the array.
Using unshift():
The unshift() method adds one or more elements to the beginning of an array and returns the new
length of the array.
Using splice():
This 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).

Using length property:


The length property provides an easy way to append a new element to an array.
Example
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits+"<br>");
fruits[fruits.length] = "Kiwi";
document.write(fruits+"<br>");
fruits[fruits.length] = "Chikoo";
document.write(fruits);
</script>
Sorting Elements in an Array:
JavaScript provides the sort() method to sort the elements of an array in place and returns the
sorted array.
Example
let numbers = [5, 2, 8, 1, 4];
numbers.push(7);
console.log("Array before sorting:", numbers);
numbers.sort((a, b) => a - b);
console.log("Array after sorting:", numbers);

18. Develop JavaScript to convert the given character to Unicode and vice-versa
• JavaScript String charAt() Method
• 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.
• Syntax
• The charAt() method is represented by the following syntax:
String.charAt(index)

Example1
<html>
<body>
<title>JavaScript String charAt() Method</title>
<script>
var str="Sandip Polytechnic";
document.writeln(str.charAt(4));
</script>
</body>
</html>

• JavaScript String charCodeAt() Method


• The JavaScript string charCodeAt() method is used to find out the Unicode value of a character at
the specific index in a string.
• The index number starts from 0 and goes to n-1, where n is the length of the string.
• It returns NaN if the given index number is either a negative number or it is greater than or equal
to the length of the string.
• Syntax : string.charCodeAt(index)
• Parameter : index - It represent the position of a character.
• Return : A Unicode value
<html>
<head>
<title>JavaScript String charCodeAt() Method</title>
</head>
<body>
<script type = "text/javascript">
var str = new String( "Sandip Polytechnic" );
document.write("str.charCodeAt(0) is:" + str.charCodeAt(0));
document.write("<br />str.charCodeAt(1) is:" + str.charCodeAt(1));
document.write("<br />str.charCodeAt(2) is:" + str.charCodeAt(2));
document.write("<br />str.charCodeAt(3) is:" + str.charCodeAt(3));
document.write("<br />str.charCodeAt(4) is:" + str.charCodeAt(4));
document.write("<br />str.charCodeAt(5) is:" + str.charCodeAt(5));
</script>
</body>
</html>

19. write a javascript function to generate fibonacci series till user defined limit
<html>
<head>
<title> Fibonacci Series in JavaScript </title>
</head>
<body>
<script>
// declaration of the variables
var n1 = 0, n2 = 1, next_num, i;
var num = parseInt (prompt (" Enter the limit for Fibonacci Series "));
document.write( "Fibonacci Series: ");
for ( i = 1; i <= num; i++)
{ document.write (" <br> " + n1); // print the n1
next_num = n1 + n2; // sum of n1 and n2 into the next_num

n1 = n2; // assign the n2 value into n2


n2 = next_num; // assign the next_num into n2
}

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

20. Write a JavaScript program that will remove the duplicate element from an array.
<html>
<head>
<script>
function getUnique(arr){
var uniqueArr = [];
// loop through array
for(let i of arr) {
if(uniqueArr.indexOf(i) === -1) {
uniqueArr.push(i);
}
}
document.write(uniqueArr);
}
var array = [1, 2, 3, 2, 3];
// calling the function
// passing array argument
getUnique(array);
</script>
</head>
<body></body>
</html>

21. Write and explain a string functions for converting string to number and number to string
Using the String() function
• This method accepts an integer or floating-point number as a parameter and converts it into
string type.
Syntax:
String(object);

• Using the parseInt() method: JavaScript parseInt() Method is used to accept the string and
radix parameter and convert it into an integer.
Syntax:
parseInt(Value, radix)

Converting String to Number


<html>
<body>
<p>parse different strings.</p>
<script>
function myFunction() {
var a = parseInt("10") + "<br>";
var b = parseInt("10.00") + "<br>";
var n = a + b;
document.writeln(n);
}
myFunction();
</script>
</body>
</html>

Converting Number to String


<html>
<head>
<title>JavaScript String toString() Method</title>
</head>
<body>
<script type = "text/javascript">
var str = "Welcome To Sandip Polytechnic";
document.write(str.toString( ));
</script>
</body>
</html>
22. Write an HTML script that accepts Amount, Rate of interest and Period from user. When user
submits the information a JavaScript function must calculate and display simple interest in a
message box. (Use formula S.I. = PNR/100)
<html>
<body>
<script>
var P = parseInt(prompt(“Enter the principal amount:”));
var N = parseInt(prompt(“Enter the period:”));
var R = parseInt(prompt(“Enter the Rate of interest:”));
var SI =(P*N*R)/100;
alert(“Simple Interest is “+SI);
</script>
</body>
</html>
OR
<html>
<head>
<script>
function interest()
{
var P, N, R;
P= parseInt(document.getElementById("pr").value);
N = parseInt(document.getElementById("period").value);
R = parseInt(document.getElementById("ri").value);
var SI =(P*N*R)/100;
alert("Simple Interest is="+SI);
}
</script>
</head>
<body>
<p>Principal Amount:<input id="pr"></p>
<p>Period in Year: <input id="period"></p>
<p>Rate of Interst: <input id="ri"></p>
<button onclick="interest()"> Simple Interest</button>
</body>
</html>

23. Write HTML script that displays textboxes for accepting username and password. Write proper
JavaScript such that when the user clicks on submit button
i) All textboxes must get disabled and change the color to ‘RED; and with respective labels
ii) Prompt the error message if the password is less than six characters
<html>
<head>
<script>
function disableTxt()
{
document.getElementById("un").disabled = true;
document.getElementById('un').style.color = "red";
document.getElementById('aaa').style.color = "red";
document.getElementById("pass").disabled = true;
document.getElementById('pass').style.color = "red";
document.getElementById('bbb').style.color = "red";
}
function validateform()
{
var username=document.myform.username.value;
var password=document.myform.password.value;
if (username==null || username==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
</head>
<body>
<form name="myform" method="post" action="" onsubmit="return
validateform()" >
<label id = "aaa">Username:</label>
<input type="text" id="un" name="username"/>
<label id = "bbb">
Password:
</label>
<input type="password" id="pass" name="password"/>
<br>
<br>
<button onclick="disableTxt()">Disable Text field</button>
</form>
</body>
</html>

You might also like