Array
JavaScript arrays can grow or shrink in size after creation.
const cities = ["Sochi", "New York"];
alert("cities.length=" + cities.length);
const years = new Array(1969, 1970);
years[46] = 2015; //You can add array elements in this way.
alert("years.length=" + years.length);
alert("years=" + years);
for (let idx in years) {
alert(years[idx]);
}
Methods of Array
splice()
Cut specific elements from an array and create a new array with that elements. You can add other elements when creating a new array using splice().
slice()
It returns a new array of parts of the array.
concat()
Combines two or more arrays to return a copy of the combined array.
reverse()
It flips the order of the array.
The concat() and the slice() methods do not change the original array and return the result as a new array.
The JavaScript engine converts the array into a string separated by a comma (,).
const words = new Array('A','B','C','D','E');
const s1 = words.splice(2,2,'c','d');//Remove two elements from index 2 and add 'c' and 'd' at that position
alert(words);
alert(s1);
const s2 = words.slice(2,4);//Returns a new array from index 2 to index 3 (not including index 4).
alert(s2);
alert(words);
for .. in
const lang = ["C", "JAVA", "javascript"];
for (let idx in lang) {
alert(lang[idx]);
}
Associative arrays
Associative arrays can not access an element using an index. When you create an associative array, you typically use Object. Associative arrays also automatically adjust in size whenever you add a new element or remove an element.
const account = new Object(); account["accountNo"] = "1111-2222-3333"; account["name"] = "John Doe"; account["balance"] = 30000; alert(account["name"]); alert(account.balance);
The following shows how to access an element in an associative array.
//Access the getElementsByTagName() element of the associative array document.
document.getElementsByTagName('a');
//Access the element ceil() of the associative array Math.
Math.ceil(175);
The following statement prints all elements of the document object.
for (let property in document) {
alert(property + ":" + document[property]);
}
The above example has different results for different browsers. All JavaScript objects are an associative array.
References