How do I create arrays in JavaScript

Javascript arrays

Name and Index

An array is a variable that can contain multiple values. Instead of defining four, five or 75 variable names, Javascript uses the name of the array and addresses the individual elements via their index.

We put a variable through the keyword var or let and a name fixed. The equal sign assigns a value to the variable. An array is also a single variable with a name, only that Javascript can assign a whole range of values ​​to an array.

Instead of creating a series of variables - e.g. to create an HTML table with Javascript:

let tr = document.createElement ("TR"); let t0 = document.createElement ("TD"); let t1 = document.createElement ("TD"); let t2 = document.createElement ("TD"); let t3 = document.createElement ("TD");

An array is more efficient:

let tr = document.createElement ("TR"); let td = []; for (let i = 0; i <4; i ++) {td [i] = document.createElement ("TD"); tr.appendChild (td [i]); }

Javascript only knows 6 data types (boolean, number, string, null, undefined and object). Arrays are not on the list because arrays are objects. The Javascript interpreter knows that the square brackets create an array.

let items = [1, 3, 5, 7, 11];

Shorthand and notation for arrays

Instead of setting each value individually, the short notation is sufficient.

let colors = ["green", "red", "blue", "black"];

The last element should not be followed by a comma - otherwise the comma could lead to inconsistent behavior in the browser (is there still an empty element after it or not?).

Javascript is not a simple data type arraybut an array is a Javascript Object - a composite data type.

The array index

The individual values ​​are addressed by their index and can be of different nature: Integer, String, Boolean or again an array. The index always starts at 0.

let myarray = []; myarray [0] = "yellow"; myarray [1] = "green"; myarray [2] = 18; myarray [3] = false;

Javascript reads the values ​​of an array with the same notation:

console.log (myarray [1]); // outputs "green"

or go straight to the point

console.log (myarray); //

Arrays come in many programming languages. Javascript programming without arrays is inconceivable. Hardly any script can do without arrays.

In Javascript, arrays do not need a size, the number of places in the array does not have to be specified when defining the variables. If you come from C or Java: In reality, Javascript arrays are hash tables and do not form a contiguous memory.

Traverse array

One of the practical aspects of arrays - in addition to the common name for all elements - is that Javascript can iterate over the elements of the array with a for loop. If the array has more than a handful of elements, iteration is far more efficient than counting iterations.

const food = ["pizza", "pasta", "fish", "potatoes", "fries"]; const foodLength = food.length; for (let i = 0; i Instead of the classic for loop, a forEach is more elegant for iterating an array - if only because we no longer even have to probe the number of elements.

const elements = ["bull.jpg", "rabbit.jpg", "snail.jpg"]; elements.forEach (function (image, index) {const img = document.createElement ("img"); img.src = elements [index]; document.querySelector (". running"). appendChild (img);});

Looping through an array is even easier for of without a callback. for of has been added in ES6 and replaces both for in as well as forEach. for of runs over arrays, strings and maps (not IE11, not EDGE)

for (var element of elements) {const img = document.createElement ("IMG"); img.src = elem; document.querySelector (". running"). appendChild (img); }

Define array

Therefore there are several methods to create a Javascript array: the literal (literal) notation with square brackets (mostly used) and the explicit array constructor with the keyword new Array (which you can just as easily omit).

All notations produce the same array:

let color = []; // literal notation let color = new Array (); // Object let color = Array (); // Object, new is not required

The difference to the literal notation is slight. Round brackets replace the square brackets and the array constructor is explicitly listed.

let myBooks = new Array (); myBooks [0] = "Emma", myBooks [1] = "Pride and Prejudice", myBooks [2] = "Off the Post", myBooks [3] = "The Perfume"); or abbreviated: let myBooks = new Array ("Emma", "Pride and Prejudice", "Off the Post", "The Perfume");

In addition to the small additional effort required for a few letters, the constructor syntax has other disadvantages.

Literal notation or object?

When is it better to use a literal array and when is it better to use a simple array object?

An array has a predefined property length, on the other hand, simple objects have no such property. "Real" arrays extend the simple array object with practical properties such as length, have a numeric index and methods like push () and pop().

If the order of the elements is a concern, a literal array is always appropriate.

When order is not important, an array object provides quick access to key / value pairs.

let myPlaces = Array (); myPlaces ['A'] = "Aachen"; myPlaces ['B'] = "Berlin"; myPlaces ['C'] = "Dortmund"; console.log ('Favorite Places' + myPlaces.length); // returns 0

An array object can be created with a certain length.

let myBooks = Array (4)

This array has four places. Basically there are no restrictions. If an element is added to place 5, that's enough myBooks [5] = "The Swarm". If we want an element in number 100, we write myBooks [100] = "History of Literature".

The spelling is confusing? Array objects are created with round brackets, the elements are called with square brackets.

However, since Javascript arrays do not have to allocate memory in advance when they are generated, and the length can be extended at any time, this option for array objects only has a dubious advantage.

The size or length or number of elements in an array

Because arrays are objects, there is information about the array - Properties. Most of the time we are interested in the size or number of elements in the array.

let color = ["red", "yellow", "green", "blue", "ocher", "orange", "purple"]; let length = color.length;

The size of the array is not that simple, because length simply returns the largest index of the array plus 1. That sounds insidious, but it is quite efficient, because Javascript saves counting the elements.

The value of length can also be set. If length is set to 0, the array is cleared.

let arr = [0, 1, 2, 3, 4]; // 5 console.log ("arr length" + arr.length); arr [20] = 2; // 21 console.log ("arr length" + arr.length);

Find out if the object is an array

To find out whether an object is an array, EcmaScript 5 threw out a special solution: Array.isArray (obj). isArray returns true if the object is an array and false otherwise.

let month = ["January", "February", "March", "April"]; console.log ("*** an array?" + Array.isArray (month)); *** an array? true

Methods for Javascript arrays

Methods is the name for functions that belong to an object. Methods of objects are called with the name of the object (followed by a period followed by the name of the method).

The ready-made methods for Javascript do the typical recurring work with arrays.

color.reverse ();

reverse () reverses the order of the elements in the array.

elem.getElementsByTagName and elem.children are well-known methods of the DOM that return an array and that we encounter in countless scripts.

push (), pop (), shift () and more: insert elements after the last element, remove the last element, append several arrays to one another or convert the elements of an array into strings: these are practical methods, even if they are not used in each Script can be used for arrays.

  • push
  • pop
  • shift
  • slice
  • splice
  • sort
  • unshift
  • reverse
  • concat
  • join
  • forEach
  • every
  • some
  • map
  • filter

External sources