Java script arrays

46
Arrays

Transcript of Java script arrays

Page 1: Java script arrays

Arrays

Page 2: Java script arrays

Arrays Declaring and Allocating ArrayTypes of ArrayArray Methods

TOPICS

Page 3: Java script arrays

ArraysArray inherits from Object.Indexes are converted to strings and used as names for retrieving values.Not very efficient in most other cases.The JavaScript Array object is a global object that is used in the construction of arrays; which are high-level, list-like objects.One advantage: No need to provide a length or type when creating an array.

Page 4: Java script arrays

Normally, arrays allocate a contiguous block of memory of fixed length. However, in Javascript, arrays are: Object types with special constructors and accessor methods.

Which means, a statement like:

var arr = new Array(100000);does not allocate any memory! In fact, it simply sets the value of the length property in the array. When you construct an array, you don't need to declare a size as they grow automatically.

Page 5: Java script arrays

So, you should use this instead:var arr = [];Arrays in Javascript are sparse which means not all the elements in the array may contain data. In other words, only the elements that actually contain data exist in the array. This reduces the amount of memory used by the array. The values are located by a key and not by an offset. They're simply a method of convenience and not intended to be used for complex numerical analysis.

Arrays in Javascript are not typed so the value of an element can be an object, string, number, boolean, function or an array.

Page 6: Java script arrays

Declaring and Allocating ArraysJavaScript arrays are Array objects.

Creating new objects using the new operator is known as creating an instance or instantiating an object

Operator new is known as the dynamic memory allocation operator

Page 7: Java script arrays

Declare + Initialize ArraysOnly declaration

var arr=[];

Using the conventional Syntax

var arr = [“a” , ”b” , ”c”];

Using the JavaScript Keyword new

var arr = new Array(“1”,”2”,”3”,”4”);document.write(arr[0]+arr[1]+arr[2]+arr[3]);

Page 8: Java script arrays

Types of Array

Associative Array Index Array

Page 9: Java script arrays

Associative Array

//Associative array examplevar  person ={ firstName: "Frayosh", Lastname:"Wadia“ }; document.write(""+person["firstName"]+

“ ”+person["Lastname"] );

Javascript associative array is a type of array which stores data using name value pairs The array data can be accessed by specifying the key rather than the index

Output : Frayosh Wadia

Page 10: Java script arrays

Indexing Array

//Indexing Array

<script> var ary = ["A", "B" , "C" , "D" , "E","F"];

document.write(“<br>"+ary[4]); <script>

Output : E

Page 11: Java script arrays

USING LOOP

//Using Loop and iterating the array

<script>var arr=new Array(“1”,”2”,”3”,”4”);

for(i=0;i<ary.length;i++){document.write(ary[i]);}

</script>

Output : 1234

Page 12: Java script arrays

Array Methods Concat Join Push Pop Unshift Shift Sort Reverse Slice Splice IndexOf LastIndexOf Length

Page 13: Java script arrays

CONCATJavascript array concat() method returns a new array comprised of this array joined with two or more arrays.

Syntax:The syntax of concat() method is as follows −

array.concat(value1, value2, ..., valueN);

Return Value:Returns the length of the array.

Page 14: Java script arrays

//Array method Concat

<script> var a=new Array("Hello"); var b=new Array("World"); document.write("<br>"+a.concat(b));</script>

Output :Hello,World

Page 15: Java script arrays

JoinJavascript array join() method joins all the elements of an array into a string.

SyntaxIts syntax is as follows −array.join(separator);

Parameter Detailsseparator − Specifies a string to separate each element of the array.

Return ValueReturns a string after joining all the array elements.

Page 16: Java script arrays

//Array Method: Join

<script>var c=new Array(6,7,8,9);document.write("<br>"+c.join("/"));</script>

Output : 6/7/8/9

Page 17: Java script arrays

PUSHJavascript array push() method appends the given element(s) in the last of the array and returns the length of the new array.

SyntaxIts syntax is as follows −array.push(element1, ..., elementN);

Parameter Detailselement1, ..., elementN: The elements to add to the end of the array.

Return ValueReturns the length of the new array.

Page 18: Java script arrays

// Array Method Push

<script>var d=new Array("Frayosh","Lalit","Sameer");d.push("Muzzamil");document.write("<br>"+d);</script>

Output :Frayosh,Lalit,Sameer,Muzzamil

Page 19: Java script arrays

POPJavascript array pop() method removes the last element from an array and returns that element.

SyntaxIts syntax is as follows −array.pop();

Return ValueReturns the removed element from the array.

Page 20: Java script arrays

// Array method pop

<script>var e=new Array(1,2,3,4);e.pop();document.write("<br>"+e);</script>

Output :1,2,3

Page 21: Java script arrays

UNSHIFTJavascript array unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

SyntaxIts syntax is as follows −array.unshift( element1, ..., elementN );

Parameter Detailselement1, ..., elementN − The elements to add to the front of the array.

Return ValueReturns the length of the new array.

Page 22: Java script arrays

// Array method: Unshift

<script>var f=new Array("Frayosh","Lalit","Sameer");f.unshift("Muzzamil");document.write("<br>"+f);</script>

Output :Muzzamil,Frayosh,Lalit,Sameer

Page 23: Java script arrays

SHIFTJavascript array shift()method removes the first element from an array and returns that element.

SyntaxIts syntax is as follows −array.shift();

Return ValueReturns the removed single value of the array.

Page 24: Java script arrays

// Array Method: Shift

<script>var g=new Array(1,2,3,4);g.shift();document.write("<br>"+g);</script>

Output : 2,3,4

Page 25: Java script arrays

SORTJavascript array sort() method sorts the elements of an array.

SyntaxIts syntax is as follows −array.sort();

Return ValueReturns a sorted array.

Page 26: Java script arrays

//Array Method:Sort

<script>var h=new Array("Frayosh","Lalit","Sameer","Muzzamil");h.sort();document.write("<br>"+h);</script>

Output : Frayosh,Lalit,Muzzamil,Sameer

Page 27: Java script arrays

REVERSEJavascript array reverse() method reverses the element of an array. The first array element becomes the last and the last becomes the first.

SyntaxIts syntax is as follows −array.reverse();

Return ValueReturns the reversed single value of the array.

Page 28: Java script arrays

// Array method: Reverse

<script>var i=new Array(4,7,2,1);

document.write("<br>"+i.reverse());</script>

Output :1,2,7,4

Page 29: Java script arrays

SLICEJavascript array slice() method extracts a section of an array and returns a new array.

SyntaxIts syntax is as follows −array.slice( begin ,end);

Parameter Detailsbegin − Zero-based index at which to begin extraction

end − Zero-based index at which to end extraction.

Return ValueReturns the extracted array based on the passed parameters.

Page 30: Java script arrays

//Array Method: Slice

<script>var k=new Array("A","B","C","D","E");document.write("<br>"+j.slice(1,4));

<script>

Output :B,C,D

Page 31: Java script arrays

//Array Method:Slice

<script>var j=new Array("A","B","C","D","E");document.write("<br>"+j.slice(2));<script>

Output : C,D,E

Page 32: Java script arrays

Javascript array splice() method changes the content of an array, adding new elements while removing old elements.

SyntaxIts syntax is as follows −array.splice(index, howMany, [element1][, ..., elementN]);

Parameter Detailsindex − Index at which to start changing the array.

howMany − An integer indicating the number of old array elements to remove.

element1, ..., elementN − The elements to add to the array.

Return ValueReturns the extracted array based on the passed parameters.

Splice

Page 33: Java script arrays

Remove Values

//Splice method used for removing elements

var j=new Array("A","B","C","D","E");j.splice(2,2);document.write("<br>"+j);

Output :A,B,E

Page 34: Java script arrays

//Array method :Splicevar l=new Array("A","B","C","D","E");j.splice(2,0,"S","H");document.write("<br>"+j);

Add Values

Output : A,B,S,H,C,D,E

Page 35: Java script arrays

ADD & REMOVE

//Splice method used for adding and removing elements

var j=new Array("A","B","C","D","E"); j.splice(2,2,"S","H"); document.write(“<br>"+j);

Output :  A,B,S,H,E

Page 36: Java script arrays

IndexOfJavascript array indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

SyntaxIts syntax is as follows −array.indexOf(searchElement, fromIndex);

Parameter DetailssearchElement − Element to locate in the array.

fromIndex − The index at which to begin the search. Defaults to 0, i.e. the whole array will be searched.

Return ValueReturns the index of the found element.

Page 37: Java script arrays

// Array Method: IndexOf

<script>var ar=new Array("A","B","C","D","E","F","G");document.write("<br>"+ar.indexOf("F"));</script>

Output :5

Page 38: Java script arrays

Javascript array lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex.

SyntaxIts syntax is as follows −array.lastIndexOf(searchElement, fromIndex);

Parameter DetailssearchElement − Element to locate in the array.

fromIndex − The index at which to start searching backwards. Defaults to the array's length, i.e., the whole array will be searched.

Return ValueReturns the index of the found element from the last.

LastIndexOf

Page 39: Java script arrays

// Array method :Last Index Of<script>

var index = [8, 5, 8, 130, 44,8,16,15];document.write("<br>"+ index.lastIndexOf(8,6));

</script>

Output :5

Page 40: Java script arrays

LENGTHJavascript array length property returns an unsigned, 32-bit integer that specifies the number of elements in an array.

SyntaxIts syntax is as follows −array.length

Return ValueReturns the length of the array

Page 41: Java script arrays

// Array length returning the length of the array

<script>var ar=new Array("A","B","C","D","E","F","G");document.write("<br>"+ar.length);</script>

Output :7

Page 42: Java script arrays

Adding ElementsJavascript allows you to declare and empty array and add values later on

Eg. var cities=[]; cities[0]="Delhi";

cities[1]="Mumbai";cities[2]="Chennai";cities[3]="Bangalore";

orYou can simply add values during declaration

Eg. var cities=[“Delhi",“Mumbai",“Chennai",“Bangalore"];

orCreate an Array instance(new) and add values

Eg. var cities=new Array(“Delhi”,”Mumbai”,”Chennai”,”Bangalore”);

Page 43: Java script arrays

Deleting Elementsdelete array[number]

Removes the element, but leaves a hole in the numbering. Returns Boolean value

array.splice(number, 1)

Removes the element and renumbers all the following elements. Returns the deleted value.

Page 44: Java script arrays

Deleting Elements//deleting Elements using delete

var cities=["Delhi","Mumbai","Chennai","Bangalore"];delete cities[1];document.write("<br>Array after using delete :"+ cities);document.write("<br>Displaying element at 1st position:"+cities[1]);

OutputArray after using delete :Delhi,,Chennai,BangaloreDisplaying element at 1st position:undefined

Page 45: Java script arrays

//deleting using splice

<script>

var cities=["Delhi","Mumbai","Chennai","Bangalore"];document.write("<br>Deleted Element:"+cities.splice(1,1));document.write("<br>Array after using splice:"+ cities);document.write("<br>Displaying element at 1st position:"+

cities[1]);</script>

OutputDeleted Element:MumbaiArray after using splice:Delhi,Chennai,BangaloreDisplaying element at 1st position:Chennai

Page 46: Java script arrays

THANKSFORWATCHING