Introduction
An array is declared using square-bracketed notation as in the following:
- var names = ["Abhi", "Ayush", "Abhijeet"]
To get an element put its index in square brackets (the first index is 0) as in the following:
- var names = ["Abhi", "Ayush", "Abhijeet"]
- alert(names[0])
- alert(names[1])
- alert(names[2])
We can also retrieve its length as in the following:
- var names = ["Abhi", "Ayush", "Abhijeet"]
- alert(names.length)
Methods pop and push
There is a method pop that removes the last item and returns it.
Here we will see how the “abhijeet” is being popped off.
- var names = ["Abhi", "Ayush", "Abhijeet"]
- alert("I remove " + names.pop())
-
- alert("Now length is: " + names.length)
There is another method push that appends an element to the array.
Let’s say we’ve forgotten Bittoo as in the following:
- var names = ["Abhi", "Ayush"]
- names.push("Bittoo");
-
- alert("Last element is:" + names[names.length - 1])
Iterating over an array
To iterate over elements, a loop over all indices is usually used as in the following:
- var names = ["Ab", "Yogi", "Abhi", "Ayush", "Bittoo"]
- for (var i = 0; i < names.length; i++) {
- alert(names[i])
- }
Multidimensional arrays
Here is an example:
- var multi = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]
- alert(multi[1][1])
join and split
- The join method combines an array into a string using a specifeid separator as in the following:
- var names = ["Ab", "Abhi", "Ayush", "Bittoo"];
- var s = names.join(', ');
- alert(s);
- The split method is the reverse of join:
- var names = "Abhi,Ayush,Bittoo";
- var ar = names.split(',');
-
- alert(ar[0]);
Removing from an array
Here is an example:
- var ar = ["Hello", "Most", "Welcome"]
- delete ar[1]
-
- alert(ar[1])
A delete operator removes a key-value pair. Basically, because an array is just a hash, the slot becomes undefined.
We need to remove an item without leaving holes between indexes. For this, there is another method known as a splice.
Method splice
Syntax
- ar.splice(index, deleteCount[, elem1,..., elemN])
It can delete elements and replace them.
Here is an example:
- var ar = ["Hello", "Most", "Welcome"]
- ar.splice(1, 1)
- alert(ar.join(','))
anotherher example.
- Splice is able to insert elements, just set the deleteCount to 0.
- var ar = ["Hello", "Most", "Welcome"];
-
-
-
- ar.splice(2, 0, "Hi", "Buddy")
- alert(ar)
Method slice
We can also extract a portion of an array using slice(begin, end).
This method does not modify the array, it just copies a slice of it.
Example
- var ar1 = ["Hello", "Most", "Welcome"];
- var ar2 = ar1.slice(0, 2)
- alert(ar2.join(', '))
Method reverse
Suppose I want the last part of a domain, like “com” from “www.abhijeet.com”.
Example
- var domname = "www.abhijeet.com"
- var l = domname.split('.').reverse()[0]
- alert(l)