Animations

API

Arrays

Async

Basics

Challenges

Classes

Console

Dates

Debugging

DOM Elements

DOM Methods

DOM Navigation

DOM Properties

Event Listeners

Flow Control

Forms

Functions

Global Functions

JSON

Keywords

Libraries (3rd party)

Math

Modules

Objects

Snippets

String

Types

Widgets

Window Object

JavaScript - Array Basics

https://www.w3schools.com/jsref/jsref_obj_array.asp

An array is a special variable, which can hold more than one value at a time.


var cars = ["Saab", "Volvo", "BMW"];
var cars = new Array("Saab", "Volvo", "BMW");

The two lines above to the exact same thing. You do not need to instantiate it with a new keyword. Arrays have zero-based indexes. They are start at 0. A 5 five item array has indexes 0-4.

Arrays with Objects

You can also initialize arrays with objects like so:


var ships =
[
    { property1: "value", property2: "value" },
    { property1: "value", property2: "value" }
]
            
        

 

Accessing by Indexes

You can access by the Index like so:


var cars2 = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars2[1];

 

Looping through an array

You can also loop through and array like so:


let ships =
[
    { Name: "X Wing", Alignment: "good" },
    { Name: "Tie Fighter", Alignment: "bad" }
]

let html = "";
for (var i = 0; i < ships.length; i++)
{
    html +=ships[i].Name + " " + ships[i].Alignment + "< br />" ;
}

let demoLabel=document.getElementById("demo");
demoLabel.innerHTML=html;

results: