An array is a container with an index that you can store in many values. You can declare an array:
var persons = ;
The above is an empty array. You can also declare an array with its values
var persons = ["Kronos", "Zeus", "Ira"];
You can access an array element using indexes, starting from 0
console.log(persons); //will print Zeus
You can change the value of an array using indexes:
persons = "Afroditi";
Arrays are objects. That means they have methods and properties which you can access using the “.” .
You can add a new element at the end using push() method
and you can delete the last element using pop() method;
length returns the size of the array. sort() sorts the array. splice(startingIndex, amount) removes elements from the array.
persons.splice(1,2); //It will remove 2nd and 3rd element
You can also have an array of objects or an array inside another array
strings are also arrays but you cannot use all the methods that an array or an object has. Those are push(), pop() and splice(). Instead strings have concat(), substring() and replace().
var str = "Kronos"; var str2 = str.concat("Zeus"); console.log(str2); str2 = str2.replace("Kro","Bra") console.log(str2); str2 = str2.substring(6, str2.length); console.log(str2);
You can also iterate an array. There are two ways: The first one is by using the foreach() method that takes a single argument. This argument is a callback function and takes up to 3 parameters:
- the current element
- the index of the current element
- the array itself
The second way is by using the loop statements: