English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
An array in JavaScript is a global object used to store multiple values in a single variable.
An array can contain any data type, including strings, numbers, objects, functions, and even other arrays.
Suppose you want to store city names in JavaScript code. Storing city names one by one in variables might look like this:
let city1 = "New Delhi"; let city2 = "Mumbai"; let city3 = "Jaipur";
But if you need to store the name of a city in a variable, it may not be just three, but possibly a hundred.
It would be a very difficult task to use so many variables at the same time and track all of them.
Arrays solve this problem by providing an ordered structure to store multiple values or a set of values in a single variable.
There are two ways to create an array in JavaScript:
Literal-Implicit creation, using brackets: []
A concise way-Direct instantiation, using the new keyword
Let's demonstrate how to use the initializedArray constantsCreate fruitsArray[]:
let fruits = ["Apple", "Mango", "Banana", "Orange"];Test See‹/›
Declarations can span multiple lines:
let fruits = [ "Apple", "Mango", "Banana", "Orange" ];Test See‹/›
Now this is usingArray constructorThe same data created, which initializes new Array():
let fruits = new Array("Apple", "Mango", "Banana", "Orange");Test See‹/›
Both methods will create an array. However,Literal-Implicit creationThe method (brackets []) is more common and preferred becausenew Array()Constructor methods may result in inconsistent and unexpected results.
Arrays do not have names/Instead of using named pairs. Instead, they are indexed with integer values starting from 0.
This is an example of an array assigned to fruits:
let fruits = ["Apple", "Mango", "Banana", "Orange"];
This is the breakdown of how each element in the fruits array is indexed:
0 | 1 | 2 | 3 |
---|---|---|---|
Apple | Mango | Banana | Orange |
The first element in the array is "Apple", with an index value of 0.
The last element is "Orange", with an index value of3.
Elements in a JavaScript array can be accessed by referencing the index number in the brackets.
let fruits = ["Apple", "Mango", "Banana", "Orange"]; fruits[0];// Returns "Apple" fruits[2];// Returns "Banana"Test See‹/›
JavaScript array indices start at zero: the index of the first element in the array is 0, the index of the second element is1, and so on.
Trying to access an element that does not exist in the array will return undefined.
fruits[7];// Returns undefinedTest See‹/›
The entire array can be accessed by referencing the array name.
let fruits = ["Apple", "Mango", "Banana", "Orange"]; document.getElementById("result").innerHTML = fruits;Test See‹/›
We can use thelengthproperty to find out how many elements are in an array.
let fruits = ["Apple", "Mango", "Banana", "Orange"]; fruits.length; // Returns 4Test See‹/›
The index of the last element is equal to the length property value minus1.
This example uses the length property to display the value of the last element:
let fruits = ["Apple", "Mango", "Banana", "Orange"]; let lastIndex = fruits.length - 1; fruits[lastIndex];Test See‹/›
In the fruits variable, we have four elements, including from 0 to3index. If you want to add a new element to the array, you can assign a value to the next index.
let fruits = ["Apple", "Mango", "Banana", "Orange"]; fruits[4] = "Guava";Test See‹/›
If we add an element and accidentally skip an index, it will create an element with an empty value ('') in the array.
fruits[6] = "Strawberry";Test See‹/›
Usingpush()The method can avoid similar problems, which adds an element to the end of the array.
let fruits = ["Apple", "Mango", "Banana", "Orange"]; fruits.push("Strawberry");Test See‹/›
You can also uselengthProperty adds a new element to the array.
let fruits = ["Apple", "Mango", "Banana", "Orange"]; fruits[fruits.length] = "Beer";Test See‹/›
By using the assignment operator, we can assign a new value to any value in the array.
let fruits = ["Apple", "Mango", "Banana", "Orange"]; fruits[0] = "Monkey";Test See‹/›
Arrays are usually used to combine lists of similar data types, but technically, they can contain any value or a mix of values.
let myArray = [5, 22, "Arrow", "Bone", true, new Date()];Test See‹/›
We can take advantage offorandlengthProperty to loop through the entire array.
In this example, we create a fruit array and print each index and each value to the document:
let fruits = ["Apple", "Mango", "Banana", "Orange"]; let txt = ""; //Traverse the length of the array for (let i = 0; i < fruits.length; i++) { txt += i + " = " + fruits[i] + "<br>"; }Test See‹/›
We can also use the followingArray.forEach()Method:
let fruits = ["Apple", "Mango", "Banana", "Orange"]; let result = document.getElementById("result"); fruits.forEach(function(element) { result.innerHTML += element + "<br>"; });Test See‹/›
We can also usefor...ofLoop to traverse JavaScript arrays, which is a new feature of JavaScript:
let fruits = ["Apple", "Mango", "Banana", "Orange"]; let result = document.getElementById("result"); for (let x of fruits) { result.innerHTML += x; }Test See‹/›
for...ofThe loop does not retrieve the index number of the elements in the array, but it is usually a simpler and more concise way to traverse the array.
Multidimensional arrays are arrays that contain one or more arrays.
let points = [ [35, 28, 29, 31], [33, 24, 25, 29] ];
JavaScript can understand arrays with a depth of2,3,4,5Or more levels of multidimensional arrays. However, for most people, it is difficult to manage arrays with more than three levels.
The dimension of the array indicates the number of indices required to select an element:
For two-dimensional arrays, you need two indices to select an element
For three-dimensional arrays, you need three indices to select an element
A two-dimensional array can be considered as a table, where the first [ ] is the row, and the second [ ] is the column.
points[0][1]; // Returns 28 points[1][0]; // Returns 33Test See‹/›
In this example, we create a two-dimensional array and print each index and value to the document:
let points = [35, 28, 29, 31],33, 24, 25, 29]; let row; let col; for (row = 0; row < 2; row++) { for (col = 0; col < 4; col++) { document.write(row, col, points[row][col]); } }Test See‹/›
Of course, you can also uselengthAttribute to get the size of rows and columns:
let points = [ [10, 12, 14, 16, 18], [20, 22, 24, 26], [30, 32, 34], [32, 34] ]; points.length;// Returns 4 (Total rows) points[0].length;// Returns 5 points[1].length;// Returns 4 points[2].length;// Returns 3 points[3].length;// Returns 2Test See‹/›
Most of the time,2Dimensional array is enough, although some places can use3Dimensional array.
In JavaScript, an array is a special type of object.
typeof operator in JavaScript returns 'Object' for arrays.
let fruits = ["Apple", "Mango", "Banana", "Orange"]; typeof fruits; // Returns "object"Test See‹/›
There is no need to use the array constructor new Array()
On the contrary, it is better to use the implicit creation method to create an array, that is, to use the bracket [] method directly, which is more common and more popular.
The following two different statements create a new empty array named scores:
let scores = new Array(); // This method is not recommended let scores = []; // Recommended method
The following two different statements create an array containing5An array of new numbers:
let scores = new Array(2, 5, 10, 28, 10); // This method is not recommended let scores = [2, 5, 10, 28, 10]; // Recommended methodTest See‹/›
The new Array() constructor may have inconsistencies and can also produce unexpected results:
let scores = new Array(10, 25); // Create an array containing two elements(10and25) array let scores = new Array(10); // Create an array containing10An array with undefined element valuesTest See‹/›
As you know, the JavaScript typeof operator returns 'Object' for arrays.
A common question is:How to know if a variable is an array?
To solve this problem, ECMAScript 5defines a new methodArray.isArray():
let fruits = ["Apple", "Mango", "Banana", "Orange"]; Array.isArray(fruits);Test See‹/›
If an object is created by a given constructor, the instanceof operator can also be used to return true:
let fruits = ["Apple", "Mango", "Banana", "Orange"]; if (fruits instanceof Array) { // statements to execute }Test See‹/›
In the following example, we will pass an array to a function:
let fruits = ["Apple", "Mango", "Banana", "Orange"]; myFunc(fruits); function myFunc(arg) { for (let elem of arg) { document.write(elem, "<br>"); } }Test See‹/›
In the following example, we will return an array from a function:
function myFunc() { let fruits = ["Apple", "Mango", "Banana", "Orange"]; return fruits; } let myArray = myFunc(); document.write(myArray);Test See‹/›