Array in JavaScript
Array in JavaScript
Array are used to represents the group of elements into a single unit or consecutive memory location. Each and every element what we are entering into the array is going to be stored in the array with the unique index starting from zero. Through the indexes we can store the data or elements into the array or we can get the elements from the array.
To declare an array in javascript we need new keyword. To create an array you use new Array(n) where n was the number of slots in the array or new Array() omitting the size of an array.
Note: Whenever we create any array in javaScript without specifying the size then it well create array object with the zero size.
Syntax
myarray = new array(5);
Example of array in JavaScript
Example
<html> <head> <script type="text/javascript"> function arrayex() { myarray = new Array(5) myarray[0] = 10 myarray[1] = 20 myarray[2] = 30 myarray[3] = 40 myarray[4] = 50 sum = 0; for (i=0; i<myarray.length; i++) { sum = sum + myarray[i]; } alert(sum) } </script> </head> <body> <input type="button" onclick="arrayex()" value="click here"> </body> </html>
Result
Function used in Array
Here we will discuss about some functions which are frequently used in array concept in JavaScript.
Function | Discription | |
---|---|---|
concat() | To concats the elements of one array at the end of another array and returns an array. | |
sort() | To sort all elements of an array. | |
reverse() | To reverse elements of an array. | |
slice() | To extract specified number of elements starting from specified index without deleting them from array. | |
splice() | It will extract specified number of elements starting from specified index and deletes them from array. | |
push() | To push all elements in array at top. | |
pop() | To pop the top elements from array. |