In the tutorial, JavaSampleApproach will introduce one of the most important data structures of JavaScript – JavaScript Array.
1. What is JavaScript Array
JavaScript Array is a structure collection like List. It is used to store multiple objects.
2. How to initial an Array
– method 1: var customers = [];
– method 2: var browsers = ["Chrome", "Safari", "Internet Explorer", "Firefox"];
– method 3: use new Array() such as var subjects = new Array("Mathematics", "Compter");
Note: for practicing, we do NOT use new Array() to initial an array. Because it is NOT clearly, and slowly for performance.
3. Array size
We can use length
property to get the size of an Array:
4. Access Array element
Array uses index number to access element.
5. Add or Remove element
For adding a new element, we can use push()
method or use length property:
To remove an element, we use pop()
method:
6. Iterating through Array
To loop an Array, we use for
statement:
7. toString
We can converts an array to a comma separated string with toString()
method:
8. Array vs Object
Type of JavaScript Array is object:
-> What is the difference between JavaScript Array vs JavaScript Object?
With JavaScript:
- arrays use numbered indexes.
- objects use named indexes.
9. Recognize an Array
To recognize a JavaScript Array, we use Array.isArray(customers)
or customers instanceof Array
:
10. Mix multiple types
JavaScript Array can contain multiple elements with difference types, such as String
, Number
, Boolean
, Date
, Array
and Object
.