Js arrays. ▍Strengths of the for…of loop. Reordering array elements in reverse order - reverse

Arrays are one of the most commonly used types of variables that allow you to store many sequential values ​​in “one place.” However, when it comes to JavaScript, there is room for improvement.

In this article, we'll look at three little-known techniques that can be used when working with arrays.

1. Adding custom properties to arrays

If you use a search to find the JavaScript definition of an array, most sources will state that this type The value of a variable is represented as an object.

Generally speaking, a lot of the things we encounter in JavaScript are objects. It would be fair to note that the language also contains “primitive” data types, but their values ​​are somehow used in properties inside objects.

2. Accessing array elements within a loop

Since array indices can only take positive values, the counting starts from zero. We can later use this index to access the array element at a given loop iteration.

ECMAScript6 introduced a way to scroll through an array without using indexes, but through new cycle for...of.

The for...of loop is designed to iterate through the elements of an array without affecting the index of the element.

Var ary = ["orange","apple","lychee"]; for (let item of ary)( console.log(item); ) // "orange", "apple", "lychee" For comparison: outputting item indices in a for loop. var ary = ["orange","apple","lychee"]; for (var item = 0; item< ary.length; item++){ console.log(item); } // 0, 1, 2

3. The number of elements is not the dimension of the array

When we talk about the size of an array, we usually think of it as the number of elements stored in it. In fact, this is not entirely true - the length property is calculated depending on the maximum index of the element.

The length property is very ambiguous. To verify this, just look at the following manipulations:

Var ary = ; ary.length = 3; console.log(ary.length); // 3 ary = "abcd"; console.log(ary.length); // 6

In the last example, it was enough to put the element in the fifth position, as a result of which the length of the array became 6. If you think that indexes from 0 to 4 will be created automatically, you will be wrong. This can be checked using the in operator.

Var ary = ; ary.length = 3; console.log(ary.length); // 3 ary = "abcd"; console.log(ary.length); // 6 console.log(0 in ary); // false

IN in this case It's fair to call the ary array "sparse".

We can also manipulate the length property to trim arrays. The example below demonstrates “losing” the element at index 5 by decrementing the length property of the ary array.

Var ary = ; ary.length = 3; console.log(ary.length); // 3 ary = "abcd"; console.log(ary.length); // 6 ary.length = 2; console.log(ary.length); // 2 console.log(ary); // undefined

Arrays

An array is an ordered collection of values. The values ​​in an array are called elements, and each element is characterized by a numeric position in the array, called an index. Arrays in JavaScript are untyped: array elements can be of any type, and different elements of the same array can have different types. Array elements can even be objects or other arrays, allowing you to create complex data structures such as arrays of objects and arrays of arrays.

JavaScript array indexes start at zero and use 32-bit integers - the first element of the array has index 0. JavaScript arrays are dynamic: they can grow and shrink in size as needed; there is no need to declare fixed array sizes when creating them, or to re-allocate memory when their sizes change.

Arrays in JavaScript are a specialized form of objects, and array indices mean little more than just property names, which coincidentally are integers.

Creating Arrays

The easiest way to create an array is to use a literal, which is a simple comma-separated list of array elements surrounded by square brackets. The values ​​in an array literal do not have to be constants - they can be any expressions, including object literals:

Var empty = ; // Empty array var numbers = ; // Array with five numeric elements var misc = [ 1.1, true, "a", ]; // 3 elements different types+ trailing comma var base = 1024; var table = ; // Array with variables var arrObj = [, ]; // 2 arrays inside containing objects

Array literal syntax allows you to insert an optional trailing comma, i.e. the literal [,] matches an array with two elements, not three.

Another way to create an array is to call the Array() constructor. You can call the constructor in three different ways:

    Call the constructor without arguments:

    Var arr = new Array();

    In this case, an empty array will be created, equivalent to the literal.

    Call the constructor with a single numeric argument specifying the length of the array:

    Var arr = new Array(10);

    In this case, an empty array of the specified length will be created. This form of calling the Array() constructor can be used to pre-allocate memory for an array if the number of its elements is known in advance. Note that this does not store any values ​​in the array.

    Explicitly specify the values ​​of the first two or more array elements or one non-numeric element in the constructor call:

    Var arr = new Array(5, 4, 3, 2, 1, "test");

    In this case, the arguments to the constructor become the values ​​of the elements of the new array. Using array literals is almost always easier than using the Array() constructor.

Reading and Writing Array Elements

Array elements are accessed using the operator. To the left of the brackets there must be an array reference. Inside the parentheses there must be an arbitrary expression that returns a non-negative integer value. This syntax is useful for both reading and writing the value of an array element. Therefore, all of the following JavaScript instructions are valid:

// Create an array with one element var arr = ["world"]; // Read element 0 var value = arr; // Write the value to element 1 arr = 3.14; // Write the value to element 2 i = 2; arr[i] = 3; // Write the value to element 3 arr = "hello"; // Read elements 0 and 2, write the value to element 3 arr] = arr;

Let me remind you that arrays are a specialized type of object. Square brackets used to access array elements act exactly the same as square brackets used to access object properties. The JavaScript interpreter converts the numeric indexes in parentheses into strings—index 1 becomes the string "1"—and then uses the strings as property names.

There's nothing special about converting numeric indexes to strings: you can do the same with regular objects:

Var obj = (); // Create a simple object obj = "one"; // Index it with integers

The thing about arrays is that when you use property names that are non-negative integers, arrays automatically determine the value of the length property. For example, above we created an array arr with a single element. It then assigned values ​​to its elements at indexes 1, 2, and 3. As a result of these operations, the value of the array's length property changed to 4.

You should clearly distinguish indexes in an array from object property names. All indices are property names, but only properties with names represented by integers are indices. All arrays are objects, and you can add properties to them with any names. However, if you touch properties that are array indices, arrays respond by updating the value of the length property as necessary.

Please note that negative and non-integer numbers can be used as array indices. In this case, numbers are converted to strings, which are used as property names.

Adding and Removing Array Elements

We've already seen that the easiest way to add elements to an array is to assign values ​​to new indices. You can also use the push() method to add one or more elements to the end of an array:

Var arr = ; // Create an empty array arr.push("zero"); // Add a value to the end arr.push("one",2); // Add two more values

You can also add an element to the end of the array by assigning a value to the arr element. The unshift() method can be used to insert an element at the beginning of an array, which shifts existing elements in the array to higher index positions.

You can delete array elements using the delete operator, just like regular object properties:

Var arr = ; delete arr; 2 in arr; // false, index 2 in the array is not defined arr.length; // 3: the delete operator does not change the length property of the array

Removing an element is similar (but slightly different) to assigning the value undefined to that element. Note that applying the delete operator to an array element does not change the value of the length property or shift down elements with higher indexes to fill the void left by deleting the element.

It is also possible to remove elements at the end of an array by simply assigning a new value to the length property. Arrays have a pop() method (the opposite of push()), which reduces the length of the array by 1 and returns the value of the removed element. There is also a shift() method (the opposite of unshift()), which removes the element at the beginning of the array. Unlike the delete operator, the shift() method shifts all elements down to a position below their current index.

Finally, there is a multi-purpose splice() method that allows you to insert, remove, and replace elements of arrays. It changes the value of the length property and shifts array elements to lower or higher indexes as needed. We will look at all these methods a little later.

Multidimensional arrays

JavaScript doesn't support "real" multidimensional arrays, but allows you to simulate them well using arrays of arrays. To access a data element in an array of arrays, simply use the operator twice.

For example, suppose the variable matrix is ​​an array of arrays of numbers. Each element of matrix[x] is an array of numbers. To access a specific number in an array, you can use the expression matrix[x][y]. Below is specific example, Where two-dimensional array used as a multiplication table:

// Create a multidimensional array var table = new Array(10); // There are 10 rows in the table for(var i = 0; i

Methods of the Array class

The ECMAScript 3 standard defines Array.prototype as a set convenient functions for working with arrays, which are available as methods of any array. These methods will be presented in the following subsections.

join() method

The Array.join() method converts all array elements into strings, joins them, and returns the resulting string. As an optional argument, you can pass a string to the method that will be used to separate the elements in the result string. If a delimiter string is not specified, a comma is used. For example, the following fragment results in the string "1,2,3":

Var arr = ; arr.join(); // "1,2,3" arr.join("-"); // "1-2-3"

reverse() method

The Array.reverse() method reverses the order of elements in an array and returns a reordered array. The permutation is performed directly in the original array, i.e. This method does not create a new array with the reordered elements, but rather reorders them in an already existing array. For example, the following snippet, using the reverse() and join() methods, results in the string "3,2,1":

Var arr = ; arr.reverse().join(); // "3,2,1"

sort() method

The Array.sort() method sorts the elements in the source array and returns the sorted array. If the sort() method is called without arguments, the sorting is done in alphabetical order (elements are temporarily converted to strings for comparison if necessary). Undefined elements are moved to the end of the array.

To sort in order other than alphabetical, you can pass a comparison function as an argument to the sort() method. This function sets which of its two arguments should come first in the sorted list. If the first argument must come before the second, the comparison function must return a negative number. If the first argument is to follow the second in a sorted array, then the function must return a number greater than zero. And if two values ​​are equivalent (that is, their order does not matter), the comparison function should return 0:

Var arr = ; arr.sort(); // alphabet order: 1111, 222, 33, 4 arr.sort(function(a,b) ( // Numerical order: 4, 33, 222, 1111 return a-b; // Returns the value 0 // depending on the sort order of a and b )); // Sort by reverse direction, from largest to smallest arr.sort(function(a,b) (return b-a));

Notice how convenient it is to use an unnamed function in this snippet. The comparison function is only used here, so there is no need to give it a name.

concat() method

The Array.concat() method creates and returns a new array containing the elements of the original array on which concat() was called and the values ​​of any arguments passed to concat(). If any of these arguments is itself an array, its elements are added to the returned array. It should be noted, however, that recursively turning an array of arrays into one-dimensional array not happening. The concat() method does not change the original array. Below are some examples:

Var arr = ; arr.concat(4, 5); // Return arr.concat(); // Return arr.concat(,) // Return arr.concat(4, ]) // Return ]

slice() method

The Array.slice() method returns a slice, or subarray, of the specified array. The two method arguments specify the start and end of the returned fragment. The returned array contains the element whose number is specified in the first argument, plus all subsequent elements, up to (but not including) the element whose number is specified in the second argument.

If only one argument is given, the returned array contains all elements from the starting position to the end of the array. If any of the arguments is negative, it determines the element number relative to the end of the array. So, argument -1 corresponds to the last element of the array, and argument -3 corresponds to the third element of the array from the end. Here are some examples:

Var arr = ; arr.slice(0,3); // Return arr.slice(3); // Return arr.slice(1,-1); // Return arr.slice(-3,-2); // Return

splice() method

The Array.splice() method is universal method, which inserts or removes elements from an array. Unlike the slice() and concat() methods, the splice() method modifies the original array on which it was called. Note that the splice() and slice() methods have very similar names, but perform completely different operations.

The splice() method can remove elements from an array, insert new elements, or do both at the same time. Array elements are shifted as necessary to create a continuous sequence after insertion or deletion.

The first argument of the splice() method specifies the position in the array from which insertion and/or deletion will be performed. The second argument specifies the number of elements that should be removed (cut) from the array. If the second argument is omitted, all array elements from the specified to the end of the array are removed. The splice() method returns an array of the removed elements or (if no elements were removed) an empty array.

The first two arguments to the splice() method specify the array elements to be removed. These arguments can be followed by any number of additional arguments specifying the elements to be inserted into the array, starting at the position specified in the first argument.

Var arr = ; arr.splice(4); // Return , arr = arr.splice(1,2); // Return , arr = arr.splice(1,1); // Return ; arr = arr = ; arr.splice(2,0,"a","b"); // Return ; arr =

push() and pop() methods

The push() and pop() methods allow you to work with arrays as if they were stacks. The push() method adds one or more new elements to the end of the array and returns its new length. The pop() method does reverse operation- removes the last element of the array, reduces the length of the array and returns the value it removed. Note that both of these methods modify the original array rather than creating a modified copy of it.

unshift() and shift() methods

The unshift() and shift() methods behave almost the same as push() and pop(), except that they insert and remove elements at the beginning of the array rather than at the end. The unshift() method shifts existing elements to larger indices to free up space, adds the element or elements to the beginning of the array, and returns the new length of the array. shift method() removes and returns the first element of the array, shifting all subsequent elements down one position to take up the space vacated at the beginning of the array.

In this lesson we will get acquainted with arrays, learn how to create them, perform operations on their elements, and also look at the basic methods and properties available when working with them.

Array concept

An array is an ordered collection of data that has a name and is an instance Array object. It consists of elements that are accessed using their index number. The numbering of elements in an array does not start from 1, but from 0.

The following figure shows a numeric array consisting of 7 elements. The elements of this array contain the following data: 1st element (0 index) - number 123, 2nd element (1st index) - number 214, 3rd element (2nd index) - number 315, etc.

//element into which we will output the array //creating a numeric array var numberArray = new Array(123,214,315,312,124,206,218); //output the array to the element having id="myP" document.getElementById("myP").innerHTML = "1 Array element: " + numberArray + "
" + "2 Array element: " + numberArray + "
" + "3 Array element: " + numberArray + "
" + "4 Array element: " + numberArray + "
" + "5 Array element: " + numberArray + "
" + "6 Array element: " + numberArray + "
" + "7 Array element: " + numberArray;

Creating (declaring) an array

Creating an array in JavaScript is done using the new operator and the Array constructor function. IN parentheses The Array constructor function can be specified with one of the following values:

  • Number. In this case this function will create an array consisting of the specified number of elements. All of these elements will have the value undefined .
  • Multiple values ​​separated by commas. In this case, the Array constructor function will create an array consisting of the specified number of elements and assign them the appropriate values.
  • Nothing. In this case, this function will create an empty array.

Unlike many other programming languages, arrays in JavaScript automatically change their size, i.e. they are inherently dynamic. Such arrays do not need to be given any dimensions. One more distinctive feature JavaScript arrays is that different elements of the same array can contain Various types data.

Working with Array Elements

In order to contact specific element array, you must specify the name of this array and its index in square brackets. This operation also called an indexing operation.

For example, let's create an empty array and add 4 text elements to it:

//creating an empty array smartphoneColors var smartphoneColors = new Array(); //assign 1 element of the array (index 0) the value "Black" smartphoneColors = "Black"; //assign the 2nd array element (index 1) to the value "White" smartphoneColors = "White"; //assign the 3rd array element (index 2) to the value "Grey" smartphoneColors = "Grey"; //assign the 4th element of the array (index 3) to the value "Blue" smartphoneColors = "Blue";

For example, let’s display the values ​​of 2 and 4 elements of the smartphoneColors array in the browser console (F12):

Console.log("2 element = " + smartphoneColors); console.log("4 element = " + smartphoneColors);

Array length (number of elements in the array)

Determining the number of elements in an array is done using the length property.

//create an array by listing the values ​​of the elements in the Array function var volumeHDDs = new Array("500Gb","1Tb","2Tb"); //assign the lengthArray variable to the length of the volumeHDDs array var lengthArray = volumeHDDs.length;

How to get the first element of an array

Getting the value of the first element of an array is done by specifying the number 0 in square brackets of this array:

//creating an array consisting of 3 elements var volumeHDDs = new Array("500Gb","1Tb","2Tb"); //getting the value of the first element of the array var firstValue = volumeHDDs;

How to get the last element of an array

The value of the last element of an array is obtained by specifying the expression array_name.length-1 in square brackets of this array:

//creating an array consisting of 3 elements var volumeHDDs = new Array("500Gb","1Tb","2Tb"); //getting the value of the last element of the array var lastValue = volumeHDDs;

Iterating over an array

Iterating over array elements is done using for loop.

For example, let’s iterate through all the elements of the array and display their values ​​in the browser console (F12):

//creating an array nameStudents, consisting of 4 elements var nameStudents = new Array("Petya","Vasya","Kolya","Maxim"); //iterate array elements from 0 to array length-1 for (var i=0; i