What is an array?
The Array object, as with arrays in other programming languages, enables storing a collection of multiple items under a single variable name and has members for performing common array operations.
Creating Arrays
// empty array with no elements
var empty = [];
// array with 2 string elements
var names = ["Ramesh", "Suresh"];
// array with elements of different types
var mixed = [true, 100, "Namaste"];
// 2 dimensional array with object literals
var array2 = [[1,{x:1, y:2}], [2, {x:3, y:4}]];
// the 3rd element is undefined
var colors = ["Red", "Green", undefined];
// no value in the 1st element, it is undefined
var hobbies = [,"Art"];
JavaScript Array Methods
Array methods are built-in functions that we can apply to our arrays. Each method has its own function that performs a specific operation on our array and returns or modifies the array accordingly.
length()
It determines the size of an array.
var names = ["Ramesh", "Suresh", "Pandu", "Muttu"];
console.log(names.length); // => 4
push()
It inserts a new element at the end of the array.
var names = ["Ramesh", "Suresh", "Pandu", "Muttu"];
names.push("Teja"); //=>["Ramesh", "Suresh", "Pandu", "Muttu","Teja"]
unshift()
It inserts a new element at the beginning of the array.
var names = ["Ramesh", "Suresh", "Pandu", "Muttu"];
names.unshift("Teja"); //=>["Teja","Ramesh", "Suresh", "Pandu", "Muttu"]
pop()
Remove an element from the end of the array.
var names = ["Ramesh", "Suresh", "Pandu", "Muttu"];
names.pop(); //=>["Ramesh", "Suresh", "Pandu"]
shift()
Remove an element from the beginning of the array.
var names = ["Ramesh", "Suresh", "Pandu", "Muttu"];
names.shift(); //=>["Suresh", "Pandu", "Muttu"]
slice()
Create a shallow copy of an array.
var names = ["Ramesh", "Suresh", "Pandu", "Muttu"];
names.slice(2); //=>["Pandu", "Muttu"]
splice()
This method can be used to insert, remove and replace elements. -It counts from 0 so it will skip the first element and continue to the last number you have given.
var names = ["Ramesh", "Suresh", "Pandu", "Muttu"];
names.splice(1,3); //=>["Ramesh"] (Removed)
var names = ["Ramesh", "Suresh", "Pandu", "Muttu"];
names.splice(1,2,"Hello","Hi");
//=>["Ramesh", "Hello", "Hi", "Muttu"] (Replaced)
There are many more array methods... I will update soon...