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

NewIchapter2CSS

Uploaded by

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

NewIchapter2CSS

Uploaded by

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

Vidyavardhini’s Bhausaheb .Vartak.

Polytechnic developed material on CSS for BVP Students Reference


CHAPTER:2 Prof. Vaghela Parvez:8097538293

Chapter 2: Adding Array Elements:


Array ,Function ,String: • The easiest way to add a new element to an
Array: array is using the push() method:
• An Array is an object in JS lets you store • var stack = new Array;
multiple values in a single variable. • stack.push(“red”);
• It stores a fixed-size collection of elements • stack.push(“green”);
of the same type. • stack.push(“yellow”);
Declaing an Initialization Array • alert(stack.toString());
1.Using an array literal is the easiest way to create • //outputs “red,green,yellow”
a JavaScript Array. • var vItem = stack.pop();
Syntax • alert(vItem); //outputs “yellow”
• var array_name = [item1, item2, ...]; • alert(stack.toString());
• You can create array by simply assigning • //outputs “red,green”
values as follows − •
• var fruits = [ "apple", "orange", "mango" ]; Sorting n Array Elements:

Proficiency in :C language\C++ language\RDBMS \Data Structure\JAVA-5th Sem\System Programming


• You will use ordinal numbers to access and • It method sorts an array alphabetically:
to set values inside an array as follows. • Eg.
• fruits[0] is the first element fruits[1] is the • fruits.sort();// Sorts the elements of fruits
second element fruits[2] is the third o/p:______________________________
element

ContactDetails:08097538293 Please share this notes for betterment of ur classmates


2. Use the following syntax to create an Array Combining an (Converting) Arrays to Strings
object − 1. The JavaScript method toString()
• var fruits = new Array( "apple", "orange", converts an array to a string of (comma
"mango" ); separated) array values.
• The Array parameter is a list of strings or
integers. When you specify a single numeric document.write( fruits.toString());
parameter with the Array constructor, you
specify the initial length of the array. The o/p _________________________________
maximum length allowed for an array is
4,294,967,295. 2. The join() method also joins all array
elements into a string. It behaves just like
Looping Array Elements: toString(), but in addition you can specify
• The safest way to loop through an array, is the separator:
using a FOR LOOP
• <html> document.write(fruits.join(" * "));
• <body>
• <h2>JavaScript Arrays</h2> o/p _______________________________
• <script>
• var fruits, fLen, i; Changing an Array Element:
• fruits = ["Banana", "Orange", "Apple", "Mango"]; • This statement changes the value of the
• fLen = fruits.length; first element in cars :
• for (i = 0; i < fLen; i++) { •
• document.write( "<br>" + fruits[i] ); fruits[0] = "Banana";
•} o/p _______________________________
• </script>
• </body></html> Associative Arrays:
var fruits = ["Kiwi", "Orange", "Apple", "Mango" ]; • Many programming languages support
arrays with named indexes.

11
11
Vidyavardhini’s Bhausaheb .Vartak.Polytechnic developed material on CSS for BVP Students Reference
CHAPTER:2 Prof. Vaghela Parvez:8097538293

• Arrays with named indexes are called associative Example: Prototype Property
arrays (or hashes). • <html>
• JavaScript does not support arrays with named • <head>
indexes. • <title>User-defined objects</title>
• In JavaScript, arrays always use numbered • <script type = "text/javascript">
indexes. • function book(title, author) {
• In JavaScript, arrays use numbered indexes. • this.title = title;
• In JavaScript, objects use named indexes • this.author = author; }
• Objects use names to access its "members". In • </script> </head>
this example, • <body>
• var person = { • <script type = "text/javascript">
• firstName:"Parvez", • var myBook = new
• lastName:"Vaghela", book("Perl","Vaghela");
• age:46}; • book.prototype.price = null;
• person.firstName myBook.price = 100;

Proficiency in :C language\C++ language\RDBMS \Data Structure\JAVA-5th Sem\System Programming


• returns Parvez: • document.write("Book title is : " +
Array Properties: myBook.title + "<br>");
Sr.No. Property & Description • document.write("Book author is : " +
myBook.author + "<br>");
constructor Returns a reference to the • document.write("Book price is : " +

ContactDetails:08097538293 Please share this notes for betterment of ur classmates


1 array function that created the object. myBook.price + "<br>");
• </script>
Index • </body>
2 The property represents the zero-based • </html>
index of the match in the string Output:
Input Book title is : Perl
3 This property is only present in arrays Book author is : Vaghela
created by regular expression matches. Book price is : 100
length Reflects the number of elements in
4 • <html>
an array.
• <body>
prototype The prototype property allows • <script type = "text/javascript">
5 you to add properties and methods to an • var alpha = ["a", "b", "c"];
object. • var numeric = [1, 2, 3];
• var alphaNumeric = alpha.concat(numeric);
Example: length Property • document.write("alphaNumeric : " +
• <html> alphaNumeric );
• <head> • </script>
• <title>JavaScript Array length Property</title> • </body></html>
• </head> • OUTPUT: alphaNumeric : a,b,c,1,2,3
• <body>
• <script type = "text/javascript">
• var arr = new Array( 10, 20, 30 );
• document.write("arr.length is : " + arr.length);
• </script>
• </body>
• </html>
• Output: arr.length is : 3

12
12
Vidyavardhini’s Bhausaheb .Vartak.Polytechnic developed material on CSS for BVP Students Reference
CHAPTER:2 Prof. Vaghela Parvez:8097538293

Sr.No. Method & Description splice() Adds and/or removes elements from
15
concat() Returns a new array comprised of an array.
1 this array joined with other array(s) and/or toString() Returns a string representing the
16
value(s). array and its elements.
every() Returns true if every element in this unshift() Adds one or more elements to the
2
array satisfies the provided testing function. 17 front of an array and returns the new length
indexOf() Returns the first (least) index of an of the array.
3 element within the array equal to the
specified value, or -1 if none is found. 2.2 Functions:
join() Joins all elements of an array into a Defining a Function:
4 • Functions are the heart of ECMAScript: a
string.
lastIndexOf() Returns the last (greatest) collection of statements that can be run
5 index of an element within the array equal anywhere at anytime.
to the specified value, or -1 if none is found. • Functions are declared with the keyword
function, followed by a set of arguments,

Proficiency in :C language\C++ language\RDBMS \Data Structure\JAVA-5th Sem\System Programming


map() Creates a new array with the results
and finally by the code to execute
6 of calling a provided function on every
element in this array. enclosed in braces.
Advantage of JavaScript function
pop() Removes the last element from an
7 1. Code reusability: We can call a
array and returns that element.

ContactDetails:08097538293 Please share this notes for betterment of ur classmates


push() Adds one or more elements to the f unction several times so it save
8 end of an array and returns the new length coding.
of the array.
2. Less coding: It makes our program
reduce() Apply a function simultaneously
compact. We don’t need to write
9 against two values of the array (from left-to-
right) as to reduce it to a single value. many lines of code each time to
reverse() Reverses the order of the elements perf orm a common task.
of an array -- the first becomes the last, and
the last becomes the first. • The basic syntax is:
10 • function functionName(arg0,arg1,...,argN) {
var aColors = [“red”, “green”, “blue”];
aColors.reverse(); ……….statements
alert(aColors.toString());o/p“blue,green,red” •}
shift() Removes the first element from an • For example:
array and returns that element. • function sayHi(sName, sMessage) {
var queue = [“red”, “green”, “yellow”]; • alert(“Hello “ + name + “,” + sMessage);
queue.push(“black”); •}
11 alert(queue.toString()); 2.3 Calling a Functions:
//outputs “red,green,yellow,black” • This function can then be called by using
var sNextColor = queue.shift(); the function name, followed by the
alert(sNextColor); //outputs “red” function arguments enclosed in
alert(queue.toString()); parentheses (and separated by commas,
if there are multiple arguments).
slice() Extracts a section of an array and
12
returns a new array. • The code to call the sayHi() function looks
like this:
some() Returns true if at least one element
• sayHi(“PARVEZ”, “how are you today?”);
13 in this array satisfies the provided testing

function.
• function testFunc() {
14 sort() Sorts the elements of an array

13
13
Vidyavardhini’s Bhausaheb .Vartak.Polytechnic developed material on CSS for BVP Students Reference
CHAPTER:2 Prof. Vaghela Parvez:8097538293

• //leave the function blank • function sayHi(sName, sMessage) {


• } • alert(“Hello “ + sName + “,” + sMessage);
• The value undefined is returned when a function • }
doesn’t explicitly return a value, as in the • It can also be defined like this:
following: • var sayHi = new Function(“sName”,
• alert(testFunc() == undefined); //outputs “true” “sMessage”, “alert(\”Hello \” + sName +
• If a function or method is supposed to return an \”, \” + sMessage + \”);”);
object, it usually returns null when the object • functions are just reference types and they
isn’t found. always behave as if using the Function
No overloading: class explicitly created for them.
• function doAdd(iNum) { • Even though it’s possible to create a
alert(iNum + 100); function using the Function
} constructor, it’s best to avoid it
• function doAdd(iNum) { because it’s slower than defining the
alert(iNum + 10); function in the traditional

Proficiency in :C language\C++ language\RDBMS \Data Structure\JAVA-5th Sem\System Programming


} manner.However, all functions are
• doAdd(10); considered instances of Function
• What do you think will be displayed from Scope:
this code snippet? The alert will show “20”, • Programmers in any language understand
because the second doAdd() definition the concept of scope, meaning the area

ContactDetails:08097538293 Please share this notes for betterment of ur classmates


overwrites the first. Although this can be in which certain variables are accessible.
annoying to a developer, you have a way • Scopes in reference to ECMAScript is almost
to work around this limitation by using the a debatable point because only one
arguments object. scope of these three exists: the public
• By using the arguments object to scope. All properties and methods of all
determine the number of arguments objects in ECMAScript are public. You
passed into the function, it is possible to must take great care, therefore, when
simulate the overloading of functions: defining your own classes and objects.
• function doAdd() { Keep in mind that all properties and
if(arguments.length == 1) { methods are public by default.
alert(arguments[0] + 10); • This problem has been tackled by many
} else if (arguments.length == 2) { developers online trying to come up with
alert(arguments[0] + effective property scoping schemes. Due
arguments[1]); to the lack of a private scope, a
} convention was developed to indicate
} which properties and methods should be
• doAdd(10); //outputs “20” considered private. This convention
• doAdd(30, 20); //outputs “50” involves adding two underscores before
and after the actual property name. For
NOTE: ECMAScript functions don’t validate the example:
number of arguments passed against the • obj.__color__ = “red”;
number of arguments defined by the function; • In this code, the color property is intended
any developer-defined function accepts any to be private. Remember, adding these
number of arguments (up to 255, according to underscores doesn’t change the fact that
Netscape’s documentation) without causing an the property is public; it just indicates to
error. Any missing arguments are passed in as other developers that it should be
undefined; any excess arguments are ignored. considered private.

14
14
Vidyavardhini’s Bhausaheb .Vartak.Polytechnic developed material on CSS for BVP Students Reference
CHAPTER:2 Prof. Vaghela Parvez:8097538293

2.4 String: var oStringObject = new String(“hello “);


The String type is unique in that it is the only var sResult = oStringObject + “world”;
primitive type that doesn’t have a definite size. A alert(sResult); //outputs “hello world”
string can be used to store zero or more Unicode alert(oStringObject); //outputs “hello “
characters, represented by 16-bit integers The indexOf() and lastIndexOf() methods return the
position of a given substring within another string
var oStringObject = new String(“hello world”); (or –1 if the substring isn’t found).
The difference between the two is that the
Each character in a string is given a position, starting indexOf() method begins looking for the substring
with the first character in position 0, the second at the beginning of the string (character 0) whereas
character in position 1, and so on. This means that the lastIndexOf() method begins looking for the
the position of the final character in a string is substring at the end of the string. For
always the length of the string minus 1 example:
var oStringObject = new String(“hello
The String class has one property, length, which world”);

Proficiency in :C language\C++ language\RDBMS \Data Structure\JAVA-5th Sem\System Programming


gives the number of characters in the string: alert(oStringObject.indexOf(“o”));
var oStringObject = new String(“hello world”); //outputs “4”
alert(oStringObject.length); //outputs “11 alert(oStringObject.lastIndexOf(“o”));
// outputs “7”
Both valueOf() and toString() return the String

ContactDetails:08097538293 Please share this notes for betterment of ur classmates


primitive value for a String object: ECMAScript provides two methods for
alert(oStringObject.valueOf() == creating string values from a substring:
oStringObject.toString()); //outputs “true” slice() and substring().
Both methods return a substring of the string
The charAt() method returns a string containing the they act on, and both accept either one or two
character in that position: arguments. The first argument is the position
var oStringObject = new String(“hello world”); where capture of the substring begins; the
alert(oStringObject.charAt(1)); //outputs “e” second argument, if used, is the position
The character in position 1 of “hello world” is “e”, before which capture is stopped.If the second
so calling charAt(1) returns “e”. argument is omitted, it is assumed that the
If instead of the actual character you want the ending position is the length of the string
character code, then calling charCodeAt() is the var oStringObject = new String(“hello
appropriate choice: world”); alert(oStringObject.slice(3)); //“lo
var oStringObject = new String(“hello world”); world” alert(oStringObject.substring(3));
alert(oStringObject.charCodeAt(1)); // “101” This //“lo world” alert(oStringObject.slice(3, 7));
example outputs “101”, which is the character code //“lo w” alert(oStringObject.substring(3,7));
for the lowercase e character. // “lo w”

The concat() method, which is used to concatenate var oStringObject= new String(“hello world”);
one or more strings to the primitive value of the alert(oStringObject.slice(-3)); //outputs “rld”
String object. This method actually returns a String alert(oStringObject.substring(-3));
primitive value as a result and leaves the original //outputs“hello world”
String object intact: alert(oStringObject.slice(3, -4));
var oStringObject = new String(“hello “); //outputs “lo w”
var sResult = oStringObject.concat(“world”); alert(oStringObject.substring(3,-4));
alert(sResult); //outputs “hello world” //outputs “hel”
alert(oStringObject); //outputs “hello “

15
15
Vidyavardhini’s Bhausaheb .Vartak.Polytechnic developed material on CSS for BVP Students Reference
CHAPTER:2 Prof. Vaghela Parvez:8097538293

❑ Deletion — You can delete any number of items


from the array by specifying just two parameters, Additional Programs:
the starting position of the first item to delete and <htML>
the number of items to delete. <head>
For example: arr.splice(0, 2) deletes the first two </head>
items in the array arr. <body>
❑ Replacement without delete — You can insert <script language="javascript">
items into a specific position by specifying three function max(a,b,c)
parameters: the starting position, 0 (the number of {
items to delete), and the item to insert. You can if(a>=b && a>=c)
optionally specify fourth, fifth, or any number of
other parameters to insert. For example, document.write("max =a ");
arr.splice(2, 0, “red”, “green”) inserts the strings else
“red” and “green” into the array arr at position 2. if(b>=c)
❑ Replacement with delete — You can insert items

Proficiency in :C language\C++ language\RDBMS \Data Structure\JAVA-5th Sem\System Programming


into a specific position while simultaneously document.write("max =b ");
deleting items by specifying three parameters: the else
starting position, the number of items to delete,
and the item to insert. Here, you can also specify document.write("max =c ");
extra parameters to insert. The number of items to }

ContactDetails:08097538293 Please share this notes for betterment of ur classmates


insert doesn’t have to match the number of items </script>
to delete. <a
For example, arr.splice(2, 1, “red”, “green”) deletes href="javascript:max(100,200,30)">
one item at position 2 and then inserts the strings MAximim NUMBER</a>
“red” and “green” into the array arr at position 2.
</body>
Converting to a string: </HtMl>
var iNum1 = 10; var fNum2 = 10.0;
alert(iNum1.toString()); //outputs “10”
alert(fNum2.toString()); //outputs “10”
var iNum = 10;
alert(iNum1.toString(2)); //outputs “1010”
alert(iNum1.toString(8)); //outputs “12”
alert(iNum1.toString(16)); //outputs “A”

Converting to a number
var iNum1 = parseInt(“1234blue”); // 1234
var iNum2 = parseInt(“0xA”); //returns 10
var iNum3 = parseInt(“22.5”); //returns 22
var iNum4 = parseInt(“blue”); //returns NaN

var oStringObject= new String(“Hello World”);


alert(oStringObject.toUpperCase()); //outputs
“HELLO WORLD”
alert(oStringObject.toLowerCase()); //outputs
“hello world”

16
16

You might also like