Array is our first data structure.
An array lets us to group data in a list.
For example, we have a group letters A, B, C, D.
var letter = "A";
var letter = "B";
var letter = "C";
var letter = "D";
Those letter variables repeat too much, and we don't want it. Rather than having four separate variables, we can write one variable and inside of it we store those four variables.
var letters = ["A", "B", "C", "D"]; //this is array (// means comment)
Array are indexed starting at 0.
Every slot has a corresponding number. "A" (0), "B" (1), "C" (2), and "D" (3).
- We can use those indices to retrieve data. If we want to get "A" out of the array, we need to know the index of "A" which is 0.
- We can use the indices to update array value. If I want to change the "A" to "M", I can just write like this:
- We can also use the indices to add a new data. If I want to add a 5th letter "E" in the array, I will write:
We just need to give the new index and give the new value for this index.
Arrays can hold any type of data, too.
var whatever = [ 40, true, "Happy", null];
At the end, arrays have a length property.
If we want to count how many numbers inside an array, we can use length property to figure it out.
Comments
Post a Comment