Arrays. One-dimensional arrays. Creating an array. The length property. Array formation
Contents
- 1. The concept of array. Types of arrays
- 2. Declaring (creating) a one-dimensional array in JavaScript
- 3. Access to array elements. Array index properties. Adding elements to an array
- 4. Defining the size of array. The length property
- 5. Array formation by adding new elements. Change the length of the array
- 6. Examples of adding elements to the array
- Related topics
Search other resources:
1. The concept of array. Types of arrays
When developing applications, you often need to use and process a large amount of data that is of the same type or requires grouping according to some criteria. If this number reaches several tens, hundreds, thousands and even millions of units, this requires the introduction of appropriate means of group data storage and access to this data. In JavaScript, as in any other programming language, the concept of an array is introduced to process data sets of the same type.
Therefore, an array is a named collection of elements that:
- are stored sequentially in memory one after another;
- have a uniform way to access an element by indexing, so that the elements in the array are grouped.
In JavaScript, array elements can be of the same type or of different types. Each individual array element:
- has its own position in the array (index). In JavaScript, the first element of the array has index 0, the second element has index 1, and so on;
- saves the value. An array element is accessed by index.
There are the following types of arrays:
- one-dimensional. In one-dimensional arrays, the elements are arranged in a row. Access to array elements is carried out by specifying one index (position);
- multidimensional. Here the elements are formed in two, three or more dimensions. Each dimension is also a series of elements. Access to elements of multidimensional arrays is based on two, three or more indices.
⇑
2. Declaring (creating) a one-dimensional array in JavaScript
In JavaScript, a one-dimensional array is created in one of two ways:
- using the new keyword. In this case, a construct like new Array() is called;
- using square brackets []. This method is also called “literal array definition”.
⇑
2.1. Declaring an array with the new keyword
In the simplest case, declaring an array using the new operator looks like this:
var ArrayName = new Array(value1, value2, ..., valueN)
here
- ArrayName – the name of array;
- value1, value2, valueN – values that fill the elements of the array. You can also specify the names of previously declared variables here. Accordingly, the values of these variables will be inserted into the array. The array dimension (number of parts) is set to N.
If you need to create an array that does not contain a single element (the so-called “empty” array), then the declaration syntax is as follows
var ArrayName = new Array()
where ArrayName is the name of the array being created.
Example.
The example demonstrates the creation of arrays using the new operator.
// Array // Creating an array with the new operator // 1. Create an empty array var EmptyArray = new Array() // 2. Create an array of 5 numbers of type int. var AI = new Array(7, 10, 2, 5, -3) // 3. Print AI array to screen as a string document.write("AI:<br>") for (var i=0; i<AI.length; i++) document.write(AI[i]+" ") document.write("<br>") // 4. Create an array of 4 strings and display it on the screen var Seasons = new Array("Winter", "Spring", "Summer", "Autumn") document.write("Seasons:<br>") for (var i=0; i<Seasons.length; i++) document.write(Seasons[i]+" ") document.write("<br>") // 5. Create an array of objects of different types var AObj = new Array("Hello, world!", 2.88, true, '+', 3000) // 6. Create and display an array containing elements based on variables and calculations var radius = 2.5 var ResultArray = new Array( 2*Math.PI*radius, Math.PI*radius*radius, 4.0/3.0*Math.PI*radius*radius*radius ) document.write("<br>ResultArray:<br>") for (var i=0; i<ResultArray.length; i++) document.write(ResultArray[i] + "<br>") document.write("<br>")
⇑
2.2. Literal array creation. Construction []
To create an array this way, the following general syntax is used
var ArrayName = [ value1, value2, ..., valueN ]
where
- ArrayName – the name of array;
- value1, value2, valueN – array element values. Values can also be variables or the results of expression evaluations.
The following syntax is used to create an “empty” array
var ArrayName = []
where ArrayName – the name of created array.
Example.
// Arrays // Creating an array in a literal way [] // 1. Create the empty array var EmptyArray = [] // 2. Create array of 5 numbers of type int var AI = [ 7, 10, 2, 5, -3 ] // 3. Print the AI array to the screen as a string document.write("AI:<br>") for (var i=0; i<AI.length; i++) document.write(AI[i]+" ") document.write("<br>") // 4. Create an array of 4 strings and display it on the screen var Seasons = [ "Winter", "Spring", "Summer", "Autumn" ] document.write("Seasons:<br>") for (var i=0; i<Seasons.length; i++) document.write(Seasons[i]+" ") document.write("<br>") // 5. Create an array of objects of different types var AObj = [ "bestprog.net", -12.404, false, '+', 1E3 ] // 6. Create and display an array containing elements based on variables and calculations var radius = 2.5 var ResultArray = [ 2*Math.PI*radius, Math.PI*radius*radius, 4.0/3.0*Math.PI*radius*radius*radius ] document.write("<br>ResultArray:<br>") for (var i=0; i<ResultArray.length; i++) document.write(ResultArray[i] + "<br>") document.write("<br>")
Result
AI: 7 10 2 5 -3 Seasons: Winter Spring Summer Autumn ResultArray: 15.707963267948966 19.634954084936208 65.44984694978736
⇑
3. Access to array elements. Array index properties. Adding elements to an array
Once an array has been declared, the array can be used or modified. An individual array element is accessed using square brackets []
ArrayName[index]
where
- ArrayName – the name of array;
- index – position in array. It can be a number, a string, a character, and so on.
After declaring the array with some set of elements in this array, index values are formed in ascending order, starting from 0 (0, 1, 2, …). However, the JavaScript language allows any object to be used as an index. This object can be a string, a floating point number, an integer, a character, and so on. For example, in the line
ArrayName['+'] = 2.88
a cell is created with the value 2.88, but the cell index will be ‘+’. That is, in reverse operation
var c = ArrayName['+']
variable c will have the value 2.88.
If you specify a non-existent index, the result will be undefined
var A = [ 1, 2, 5] var item = A[15] // item = undefined
Example.
// Arrays. The array index // 1. The array of numbers, array indices are 0, 1, 2. var AI = [ 2, 3, 8] var t t = AI[0] // t = 2 document.write("t = " + t + "<br>") // 2. Array index - character // 2.1. Create an empty array var AC = [] // 2.2. Add items to the array AC['+'] = "Plus" AC['-'] = "Minus" AC['*'] = "Multiplication" // 2.3. Get the name by index '+' var sign = AC['+'] document.write("sign = " + sign + "<br>") // 2.4. Get name by non-existent index sign = AC['&'] // sign = undefined document.write("sign = " + sign + "<br>") // 3. Array index - string of characters // 3.1. Create an empty array var A = new Array() A["One"] = 1 A["Two"] = 2 A["Five"] = 5 // 3.2. Get element with index "Two" var number = A["Two"] document.write("number = " + number + "<br>") // 3.3. Get the element whose index is not in the array number = A["Nine"] // number = undefined document.write("number = " + number + "<br>") // 3.4. Try to get an element with an index whose name is given incorrectly // (from a lowercase letter). number = A["one"] // number = undefined document.write("number = " + number + "<br>")
Result
t = 2 sign = Plus sign = undefined number = 2 number = undefined number = undefined
⇑
4. Defining the size of array. The length property
To determine the size of an array, use the length property, which returns an integer equal to the number of array elements. The property access for the ArrayName array could be as follows
ArrayName.length
The length property is based on the highest occupied element index value in the array, not on the number of elements actually created.
Example.
// Arrays. Get the size of array. Property length // 1. Declare an empty array var EmptyArray = new Array() // 2. Get and print the size of EmptyArray array var size = EmptyArray.length // size = 0 document.write(size + "<br>") // 3. Declare an array of 3 strings var AS = [ "December", "January", "February" ] size = AS.length // size = 3 document.write(size + "<br>") // 4. Add element to AS array AS[3] = "May" size = AS.length // size = 4 document.write(size + "<br>") // 5. Add element with non-integer index to array AS AS['&'] = 123 size = AS.length // size = 4 - size has not changed document.write(size + "<br>")
Result
0 3 4 4
⇑
5. Array formation by adding new elements. Change the length of the array
An array can be created by simply adding new elements to an empty or existing array. As you know, you can use an object of string, character types, or even a floating-point numeric type (float) as an index. In this case, adding an element will not change the size of the array. If an element with an integer type index is added to the array, then the size of the array can change if the index value is greater than or equal to the current size of the array.
When adding integer elements, the following cases are considered:
- one element is added (Figure 1);
- several elements are added (Figure 2).
When adding a single element, the index of that element must be 1 greater than the maximum significant index in the array.
Figure 1. Adding one element. Increasing the length of an array by 1 (property A.length)
In the case of adding several integer elements, the index of the added element is at least 2 greater than the maximum array index (Figure 2). Intermediate array elements are filled with undefined value.
Figure 2. Adding a group of elements. Increase array length by 4 elements
⇑
6. Examples of adding elements to the array
6.1. Adding parts with non-integer indices
In the code below, elements with indexes ‘+’ and ‘-‘ are added to the array twice. In this case, the length property does not take into account these elements, although the elements are in the array. After an element with an integer index is added to the array, the length property is incremented by 1.
// Arrays. Array formation // 1. Declare an array of 3 elements of type Number var A = new Array(2, 8, 5) document.write(A.length) // 3 // 2. Add element with index '+' A['+'] = 50 // 3. Add element with index "abcd" A["abcd"] = 25 // 4. Print the length of the array again document.write("<br>" + A.length) // 3 // 5. Add element with index 3 A[3] = 100 // 6. Print the length again document.write("<br>" + A.length) // 4
Result
3 3 4
⇑
6.2. Adding elements with integer indices
The example shows an increase in the size of an array when an element is added to it with an index that is 3 positions higher than the current size of the array.
Example.
// Arrays. Array forming // 1. Declare an array of 3 elements of type Number var A = new Array(2, 8, 5) document.write("length(A) = " + A.length) // length(A) = 3 // 2. Add element with index 6 A[6] = 50 // 3. Print the length of an array and the array itself document.write("<br>length(A) = " + A.length) // length(A) = 7 document.write("<br>") for (var i = 0; i<A.length; i++) document.write(A[i] + " ") document.write("<br>")
Result
length(A) = 3 length(A) = 7 2 8 5 undefined undefined undefined 50
⇑
Related topics
- The concept of a loop. Loop statements for, while, do-while
- The for-in loop. Nested loops. Eternal loop
⇑