JavaScript - Arrays. Reordering array elements in reverse order - reverse

06/21/2017 at 12:17 pm

To calculate the size of an array of objects in JavaScript, use the length property of the array.

Var arr = ["first", "second"]; console.log(arr.length); // 2

Arrays in javascript can have gaps in their indices. For example

Var arr = ; arr = "first"; arr = "second";

The length property returns the maximum array index + 1. I.e. in the example given, length = 5.

Calculating the number of elements in an array in javascript

Array.prototype.count = function()( var result = 0; for(var i = 0; i< this.length; i++) if (this[i] != undefined) result++; return result; }

Usage example

Var arr = ; arr = "first"; arr = "second"; console.log(arr.count()); //2

You can also assign a value to the length property. This allows you to reduce the length of an existing array.

Var arr = ["first", "second", "third"]; arr.length = 2; console log(arr); // ["first", "second"]

Calculating the size of an array in bytes in javascript

Arrays are ordinary objects, so calculating the size of an array in bytes is no different than calculating the size of any other object. Unfortunately, javascript doesn't provide an API for calculating the size, so you'll have to calculate it yourself. This is done as follows: we bypass all the properties of the object, if the property is of a primitive type, we add the size of an instance of this type to the total result, if the property contains an object, we recursively calculate its size.

Function sizeOf(obj) ( var bytes = 0; if(obj !== null && obj !== undefined) ( switch(typeof obj) ( case "number": bytes += 8; break; case "string": bytes += obj.length * 2; break; case "boolean": bytes += 4; break; case "object": for(var key in obj) ( bytes += sizeOf(obj); ) break; ) ) return bytes ; );

The method is not accurate and has many problems - for example, it is likely to go into an infinite loop.

Last update: 03/26/2018

The Array object represents an array and provides a number of properties and methods with which we can manipulate the array.

Array initialization

You can create an empty array using square brackets or the Array constructor:

varusers = new Array(); var people = ; console log(users); // Array console.log(people); // array

You can immediately initialize an array with some number of elements:

Var users = new Array("Tom", "Bill", "Alice"); var people = ["Sam", "John", "Kate"]; console log(users); // ["Tom", "Bill", "Alice"] console.log(people); // ["Sam", "John", "Kate"]

You can define an array and define new elements into it as you go:

varusers = new Array(); users = "tom"; users = "kate"; console log(users); // "Tom" console.log(users); // undefined

It does not matter that by default the array is created with zero length. With the help of indexes, we can substitute one or another element for a specific index in an array.

length

To find out the length of an array, use the length property:

var fruit = new Array(); fruit = "apples"; fruit = "pears"; fruit = "plums"; document.write("In array fruit " + fruit.length + " element:
"); for(var i=0; i< fruit.length; i++) document.write(fruit[i] + "
");

In fact, the length of the array will be the index of the last element plus one. For example:

varusers = new Array(); // there are 0 elements in the array users = "Tom"; users = "kate"; users = "sam"; for(var i=0; i

Browser output:

Tom Kate 2020 Other Sam

Although we didn't add elements for indexes 2 and 3, the length of the array in this case will be the number 5. It's just that the elements at indexes 2 and 3 will have the value undefined .

Copying an array. slice()

Copying an array can be shallow or shallow (shallow copy) and deep (deep copy).

For shallow copying, it is enough to assign the value of another variable that stores the array to a variable:

var users = ["Tom", "Sam", "Bill"]; console log(users); // ["Tom", "Sam", "Bill"] var people = users; // shallow copy people = "Mike"; // change the second element console.log(users); // ["Tom", "Mike", "Bill"]

In this case, the people variable, after being copied, will point to the same array as the users variable. Therefore, when changing the elements in people, the elements in users will also change, since in fact this is the same array.

This behavior is not always desirable. For example, we want the variables to point to separate arrays after copying. And in this case, you can use deep copying with the slice() method:

var users = ["Tom", "Sam", "Bill"]; console log(users); // ["Tom", "Sam", "Bill"] var people = users.slice(); // deep copy people = "Mike"; // change the second element console.log(users); // ["Tom", "Sam", "Bill"] console.log(people); // ["Tom", "Mike", "Bill"]

In this case, after copying, the variables will point to different arrays, and we can change them separately from each other.

Also, the slice() method allows you to copy part of an array:

Var users = ["Tom", "Sam", "Bill", "Alice", "Kate"]; var people = users.slice(1, 4); console log(people); // ["Sam", "Bill", "Alice"]

The slice() method is passed a start and end index, which are used to fetch values ​​from the array. That is, in this case, the selection into the new array goes from index 1 to index 4, not including. And since array indexing starts from zero, the new array will contain the second, third and fourth element.

push()

The push() method adds an element to the end of an array:

var fruit = ; fruit.push("apples"); fruit.push("pears"); fruit.push("plums"); fruit.push("cherry","apricot
"); document.write(fruit); // apples, pears, plums, cherries, apricots

pop()

The pop() method removes the last element from the array:

Var fruit = ["apples", "pears", "plums"]; var lastFruit = fruit.pop(); // retrieve the last element from the array document.write(lastFruit + "
"); document.write("In array fruit " + fruit.length + " element:
"); for(var i=0; i ");

Browser output:

Plums Fruit array has 2 elements: apples pears

shift()

The shift() method retrieves and removes the first element from the array:

Var fruit = ["apples", "pears", "plums"]; var firstFruit = fruit.shift(); document.write(firstFruit + "
"); document.write("In array fruit " + fruit.length + " element:
"); for(var i=0; i ");

Browser output:

Apples Fruit array has 2 elements: pears plums

unshift()

The unshift() method adds a new element to the beginning of the array:

Var fruit = ["apples", "pears", "plums"]; fruit.unshift("apricots"); document.write(fruit);

Browser output:

Apricots, apples, pears, plums

Removing an element by index. splice()

The splice() method removes elements from a specific index. For example, removing elements from the third index:

Var users = ["Tom", "Sam", "Bill", "Alice", "Kate"]; var deleted = users.splice(3); console log(deleted); // [ "Alice", "Kate" ] console.log(users); // [ "Tom", "Sam", "Bill" ]

The slice method returns the removed elements.

In this case, the deletion is from the beginning of the array. If you pass a negative index, then the removal will be performed from the end of the array. For example, let's remove the last element:

Var users = ["Tom", "Sam", "Bill", "Alice", "Kate"]; var deleted = users.splice(-1); console log(deleted); // [ "Kate" ] console.log(users); // [ "Tom", "Sam", "Bill", "Alice" ]

An additional version of the method allows you to specify the end index to delete. For example, let's remove the first to third index:

Var users = ["Tom", "Sam", "Bill", "Alice", "Kate"]; var deleted = users.splice(1,3); console log(deleted); // [ "Sam", "Bill", "Alice" ] console.log(users); // [ "Tom", "Kate" ]

Another version of the splice method allows you to insert new elements in place of the removed elements:

Var users = ["Tom", "Sam", "Bill", "Alice", "Kate"]; var deleted = users.splice(1,3, "Ann", "Bob"); console log(deleted); // [ "Sam", "Bill", "Alice" ] console.log(users); // [ "Tom", "Ann", "Bob", "Kate" ]

In this case, we remove three elements from the 1st to the 3rd indices and insert two elements instead.

concate()

The concat() method is used to concatenate arrays:

Var fruit = ["apples", "pears", "plums"]; var vegetables = ["tomatoes", "cucumbers", "potatoes"]; var products = fruit.concat(vegetables); for(var i=0; i< products.length; i++) document.write(products[i] + "
");

In this case, it is not necessary to combine only arrays of the same type. You can also have different types:

Var fruit = ["apples", "pears", "plums"]; var prices = ; var products = fruit.concat(prices);

join()

The join() method concatenates all array elements into one string:

Var fruit = ["apples", "pears", "plums", "apricots", "peaches"]; var fruitString = fruit.join(", "); document.write(fruitString);

The join() method is passed a separator between array elements. In this case, a comma and a space (", ") will be used as a separator.

sort()

The sort() method sorts an array in ascending order:

Var fruit = ["apples", "pears", "plums", "apricots", "peaches"]; fruit sort(); for(var i=0; i< fruit.length; i++) document.write(fruit[i] + "
");

Output in browser:

Apricots pears peaches plums apples

reverse()

The reverse() method flips an array backwards:

Var fruit = ["apples", "pears", "plums", "apricots", "peaches"]; fruit.reverse(); for(var i=0; i< fruit.length; i++) document.write(fruit[i] + "
");

Output in browser:

Peaches Apricots Plums Pears Apples

Combined with the sort() method, you can sort an array in descending order:

Var fruit = ["apples", "pears", "plums", "apricots", "peaches"]; fruit.sort().reverse(); for(var i=0; i< fruit.length; i++) document.write(fruit[i] + "
");

Output in browser:

Apples plums peaches pears apricots

Finding the index of an element

The indexOf() and lastIndexOf() methods return the index of the first and last occurrence of an element in an array. For example:

Var fruit = ["apples", "pears", "plums", "apples", "pears"]; var firstIndex = fruit.indexOf("apples"); var lastIndex = fruit.lastIndexOf("apples"); var otherIndex = fruit.indexOf("cherries"); document.write(firstIndex); // 0 document.write(lastIndex); // 3 document.write(otherIndex); // -1

firstIndex is 0 because the first occurrence of the string "apples" in the array is at index 0 and the last at index 3.

If the element is not in the array, then the indexOf() and lastIndexOf() methods return -1.

every()

The every() method checks if all elements match a certain condition:

Var numbers = [ 1, -12, 8, -4, 25, 42 ]; function condition(value, index, array) ( var result = false; if (value > 0) ( result = true; ) return result; ); var passed = numbers.every(condition); document.write(passed); // false

The every() method is passed a function that represents the condition as a parameter. This function takes three parameters:

Function condition(value, index, array) ( )

The value parameter represents the current array element being iterated, the index parameter represents the index of that element, and the array parameter passes a reference to the array.

In this function, we can check the passed value of the element against some condition. For example, in this example, we are checking each element of the array to see if it is greater than zero. If it is greater, then we return the value true , that is, the element matches the condition. If less, then return false - the element does not match the condition.

As a result, when the numbers.every(condition) method is called, it iterates over all the elements of the numbers array and passes them in turn to the condition function. If this function returns true for all elements, then every() returns true . If at least one element does not match the condition, then the every() method returns false .

some()

The some() method is similar to the every() method, only it checks if at least one element matches the condition. And in this case, the some() method returns true . If there are no elements in the array that match the condition, then false is returned:

Var numbers = [ 1, -12, 8, -4, 25, 42 ]; function condition(value, index, array) ( var result = false; if (value === 8) ( result = true; ) return result; ); var passed = numbers.some(condition); // true

filter()

The filter() method, like some() and every() , takes a condition function. But at the same time, it returns an array of those elements that meet this condition:

Var numbers = [ 1, -12, 8, -4, 25, 42 ]; function condition(value, index, array) ( var result = false; if (value > 0) ( result = true; ) return result; ); var filteredNumbers = numbers.filter(condition); for(var i=0; i< filteredNumbers.length; i++) document.write(filteredNumbers[i] + "
");

Output in browser:

1 8 25 42

forEach() and map()

The forEach() and map() methods iterate over the elements and perform certain operations on them. For example, to calculate the squares of numbers in an array, you can use the following code:

var numbers = [ 1, 2, 3, 4, 5, 6]; for(var i = 0; i "); }

But using the forEach() method, you can simplify this construction:

var numbers = [ 1, 2, 3, 4, 5, 6]; function square(value, index, array) ( var result = value * value; document.write("The square of the number " + value + " is " + result + "
"); ); numbers.forEach(square);

The forEach() method takes as a parameter the same function that, when iterating over the elements, the current element being iterated is passed to and operations are performed on it.

The map() method is similar to the forEach method, it also takes as a parameter a function that performs operations on the iterated elements of the array, but the map() method returns a new array with the results of operations on the array elements.

For example, let's apply the map method to calculate the squares of the numbers in an array:

var numbers = [ 1, 2, 3, 4, 5, 6]; function square(value, index, array) ( return result = value * value; ); var squareArray = numbers.map(square); document.write(squareArray);

The function that is passed to the map() method gets the currently iterated element, performs operations on it, and returns some value. This value is then passed into the resulting squareArray

And as you understood from that article, only one value can be stored in a variable. How much would we try we will not write more than one value in a variable.

Let's say we declare some variable z and assign it the value 8. And if we set a different value somewhere lower in the code, let's say 3, then the old value will disappear and a new one will be written instead.

And in order to be able to write more than one value in a variable, you need to use such a data type as an array.

array allows you to write to a variable at once an unlimited number of values, of any type.

Previously, in JavaScript, an array was declared like this:

Var arr = new Array(7, 8, "k", "v", 3.2, 4);

Times have changed and now the array is declared in a different way, more abbreviated. Elements are also listed separated by commas, but already inside simple square brackets.

Var arr = [ 7, 8, "k", "v", 3.2, 4 ];

Now the arr variable is one-dimensional data array, different types.

Each element in the array has its own index. Please note that this index starts from zero. It specifies the position of an element in an array.

Array structure looks like that:

In order to refer to some element from the array, you need to write the name of the array, and in square brackets indicate the index of the element of which we want to get.

For example, let's display the element whose index is 2, that is, the letter "k".

Document.write("

We display the element of the array arr, whose index is equal to 2: " + arr + "

); // k

What if we want view all elements of an array. If there are few elements, then you can refer to each separately, as in the example, that is, arr, arr, arr.

But, if there are 100 elements in the array, then this option does not work. Here you need to use .

Before moving on to iterate over an array, I want to introduce you to the property length. This is a universal property that allows find the length of an array, which is the total number of elements in the array. It can also be used to find out the length of a string.

For fun, let's find out how long the arr array has.

Document.write("

Number of elements in array arr =" + arr.length + "

); // Result: 6

Now, in order to display all the elements at once, iterate over the entire array using a loop.

For(var i = 0; i< arr.length; i++){ document.write("

Array element arr, with index " + i + " equals: " + arr[i] + "

"); }

We open this page in the browser and see the following picture:


For practice, try looping through the "arr" array and using the rest of the while and do-while loops.

There is another simple and short variant of enumeration small array. It lies in the fact that each element of the array can be viewed using the alert method. First, we write the name of the array itself, or you can immediately specify a list of elements in square brackets. Then we write the forEach function and write the alert method as a parameter, without parentheses.

Arr.forEach(alert);

Now if we open the page in the browser, we will see each array element in turn.

Filling an Array with a Loop

For example, in a certain array, we will write the results of the multiplication table, from 1 to 10.

First you need to declare an empty array, which we will fill. Then you need to declare a variable and assign it immediately the value 0. This variable will be used as an index for the declared array. And the next step is to fill the array itself with the help of such a technique as a cycle in a cycle.

//Declare an empty array var new_arr = ; // Variable as index to array new_arr var k = 0; for(var i = 1; i

If we open this page in a browser, we will see the following result:


Initially, the variable i is equal to one. And this one is multiplied with all values ​​of the variable j. After we have gone through the second loop 10 times, we return to the first loop and increment the variable i by one. Now i is equal to two. Again we go to the second loop and multiply the value 2 by all values ​​of the variable j (from 1 to 10). The result is the second row: 2 4 6 8 ... 20. And this happens until the variable i becomes equal to 11. As soon as it takes this value, we exit the loop.

Calculate the sum of all elements from an array

We have an array new_arr which stores 100 numbers (an entire multiplication table). Now let's calculate the sum of all these elements.

//Create a variable for the sum var summ = 0; for(var i = 0; i< new_arr.length; i++){ summ += new_arr[i]; } document.write("

The sum of the elements of the new_arr array is: " + summ + "

"); //Result 3025

That's all I wanted to tell you about in this article. Now you know, how to create an array, how to fill it and how to work with it.

In practice, arrays are quite common, as they are very important in programming, so you should know them well.

Arrays

array is an ordered collection of values. The values ​​in an array are called elements, and each element is characterized by a numerical position in the array, which is 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 are zero-based and use 32-bit integers - the first element of an array has index 0. Arrays in JavaScript are dynamic: they can grow and shrink as needed; there is no need to declare fixed sizes of arrays when they are created, 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 with a literal, which is a simple comma-separated list of array elements in square brackets. Values ​​in an array literal do not have to be constants - they can be any expression, including object literals:

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

The array literal syntax allows for 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 constructor array(). You can call a constructor in three different ways:

    Call constructor with no arguments:

    Var arr = new Array();

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

    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 in the constructor call the values ​​of the first two or more elements of the array, or one non-numeric element:

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

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

Reading and writing array elements

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

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

Let me remind you that arrays are a specialized kind of objects. Square brackets used to access array elements act exactly like square brackets used to access object properties. The JavaScript interpreter converts the parenthesized numeric indexes to strings - index 1 becomes the string "1" - and then uses the strings as property names.

There is nothing special about converting numeric indexes to strings: the same can be done with ordinary objects:

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

The peculiarity of arrays is that when using property names that are non-negative integers, arrays automatically determine the value of the property length. For example, the array arr was created above 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 between array indexes and object property names. All indexes are property names, but only properties with names represented by integers are indexes. All arrays are objects, and you can add properties to them with any names. However, if you touch properties that are array indexes, arrays respond by updating the value of the length property as necessary.

Please note that it is allowed to use negative and non-integer numbers as array indexes. In this case, numbers are converted to strings, which are used as property names.

Adding and Removing Array Elements

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

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

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

Array elements can be deleted using the delete operator, just like ordinary object properties:

Var arr = ; delete arr; 2 in arr; // false, array index 2 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 undefined to that element. Note that applying the delete operator to an element of an array does not change the value of the length property, nor does it move elements with higher indices down to fill the void left by the element being deleted.

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 method pop()(opposite of push()), which decrements the length of the array by 1 and returns the value of the removed element. There is also a method shift()(opposite of the unshift() method), 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 indexes.

Finally there is a multipurpose method splice(), which allows you to insert, remove, and replace elements of arrays. It changes the value of the length property and shifts array elements with lower or higher indices as needed. We will discuss all these methods a little later.

Multidimensional arrays

JavaScript doesn't support "real" multidimensional arrays, but it does make it nice to simulate them with arrays of arrays. To access a data element in an array of arrays, it is enough to 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 matrix[x][y] expression. The following is a specific example where a two-dimensional array is used as the multiplication table:

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

Array class methods

The ECMAScript 3 standard defines a number of convenience functions for working with arrays as part of Array.prototype , 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, concatenates them, and returns the resulting string. As an optional argument to the method, you can pass a string that will be used to separate elements in the result string. If a delimiter string is not specified, a comma is used. For example, the following snippet 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 the elements in an array and returns a reordered array. The permutation is performed directly on the original array, i.e. this method does not create a new array with reordered elements, but reorders them in an already existing array. For example, the following fragment, which uses 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 original array and returns the sorted array. If the sort() method is called with no arguments, the sorting is performed in alphabetical order (the elements are temporarily converted to strings for comparison, if necessary). Undefined elements are moved to the end of the array.

To sort in some 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 the sorted array, then the function must return a number greater than zero. And if two values ​​are equivalent (i.e., their order is not important), the comparison function should return 0:

Var arr = ; arr.sort(); // Alphabetical order: 1111, 222, 33, 4 arr.sort(function(a,b) ( // Numerical order: 4, 33, 222, 1111 return a-b; // Returns value 0 // depending on sort order a and b)); // Sort backwards, 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.

concate() method

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

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

slice() method

The Array.slice() method returns a slice, or subarray, of the specified array. The two arguments to the method define the beginning 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 specifies the element number relative to the end of the array. Thus, the argument -1 corresponds to the last element of the array, and the argument -3 corresponds to the third element of the array from the end. Here are some examples:

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

splice() method

The Array.splice() method is a generic method that inserts or removes elements of 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 form a contiguous sequence after insertion or deletion.

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

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

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

push() and pop() methods

The push() and pop() methods allow arrays to be treated like stacks. The push() method adds one or more new elements to the end of the array and returns its new length. The pop() method performs the 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, not create a modified copy of it.

unshift() and shift() methods

The unshift() and shift() methods behave much like push() and pop(), except that they insert and remove elements at the beginning of the array, not at the end. The unshift() method shifts existing elements towards higher indices to free up space, adds the element or elements to the beginning of the array, and returns the new length of the array. The shift() method removes and returns the first element of the array, shifting all subsequent elements one position down to fill 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 consider the main methods and properties available when working with them.

What is an array in JavaScript?

The array is ordered collection of values. The values ​​in this collection are called elements. Each element in the array has its own serial number (number), which is called index. Indexes are numbered from 0.

The following figure shows a numeric array with 5 elements. The elements of this array contain the following data: 123 (index 0), 7 (index 1), 50 (index 2), -9 (index 3), 24 (index 4).

Creating (Declaring) an Array

Creating arrays in JavaScript is usually done with array literal.

An array literal is a square bracket containing a comma-separated list of elements.

For example:

var empty = ; // empty array var numbers = ; // numeric array var arr = ; // array containing various data types

The values ​​in a JavaScript array do not have to be of the same type. Those. One array can contain values ​​of different data types.

An array element is accessed by its index. This operation is also called the indexing operation.

For example:

// create an array of 3 elements var smartphoneColors = ["Black", "White", "Grey"]; // display in the browser console the values ​​of the smartphoneColors array elements with indexes 0 and 2 console.log("The value of the smartphoneColors array element with index 0: " + smartphoneColors); // "Value of smartphoneColors array element at index 0: Black" console.log("Value of smartphoneColors array element at index 2: " + smartphoneColors); // "The value of the smartphoneColors array element at index 0: Grey" // change the value of the smartphoneColors array element at index 1 to "Red" smartphoneColors = "Red"; // ["Black", "Red", "Grey"] // set the smartphoneColors array element at index 3 to "Blue" smartphoneColors = "Blue"; // ["Black", "Red", "Grey", "Blue"]

As values ​​of array elements, you can use not only static values, but also expressions:

var lengthA = 7, widthA = 5; var point = ;

Objects can be used as array element values.

Var points = [ (x1: 5, y1: 3), (x1: 7, y1: 10), (x1: 12; y1: 0) ]; // array consisting of 3 objects

Another way to create an array consists in calling the Array constructor function.

Calling a constructor function with no arguments is used to create an empty array.

Var empty = new Array(); // empty array

This way of creating an array is equivalent to a literal .

If you specify a number as an argument to the constructor function, then it will create an array that will consist of the specified number of elements. Moreover, all these elements will have undefined as their value.

Var arr = new Array(5); // array of 5 elements (element values ​​are undefined)

If multiple values ​​or one non-numeric value is passed to the constructor function in parentheses, it will create an array from the arguments passed to it.

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

length property (array length)

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

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

How to get the first element of an array

The value of the first element of the array is obtained by specifying the number 0 in square brackets of this array:

//create 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

Obtaining the value of the last element of the array is carried out by specifying the expression array_name.length-1 in square brackets of this array:

//create 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 the elements of an array is done using a 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("Peter","Vasya","Kolya","Maxim"); // iterate over array elements from 0 to array length-1 for (var i=0; i<= nameStudents.length-1; i++) { console.log(i+1 + " элемент массива = " + nameStudents[i]); }

What is the purpose of the delete operator

The delete operator is not used to remove an element from an array, but to assign the value of undefined to a given array element.

Var namePlanets = new Array("Venus","Mercury","Earth","Mars"); delete namePlanets; for (var i=0; i<= namePlanets.length-1; i++) { console.log(i + " элемент массива = " + namePlanets[i]); }

Functions for working with arrays (methods of the Array object)

The Array object contains the following methods (functions) for working with arrays:

  • shift
  • unshift
  • slice
  • splice
  • split
  • reverse

push method (adding an element to the end of an array)

The push method is for adding an element to the end of an array. The value of this element is specified as a parameter of this method. As a result, the push method returns the number of elements in the array, taking into account the added one.

Var namePlanets = ["Venus", "Mercury", "Earth", "Mars"]; namePlanets.push("Jupiter"); // 5 console.log(namePlanets); // ["Venus", "Mercury", "Earth", "Mars", "Jupiter"]

pop method (removing the last element from the array)

The pop method is designed to remove the last element from an array. This method has no parameters. As a result, it returns the value of the last (removed) element of the array.

Var namePlanets = ["Venus", "Mercury", "Earth", "Mars"]; namePlanets.pop(); // "Mars" console.log(namePlanets); // ["Venus", "Mercury", "Earth"]

shift method (removing the first element from the array)

The shift method is designed to remove the first element from an array, i.e. element with index 0. All other elements of the array are shifted to the beginning, i.e. for each of them, the index decreases by 1. This method returns the value of the removed element as a result.

Var namePlanets = ["Venus", "Mercury", "Earth", "Mars"]; namePlanets.shift(); // "Venus" console.log(namePlanets); // ["Mercury", "Earth", "Mars"]

unshift method (adding an element to the beginning of an array)

The unshift method is designed to add an element to the beginning of an array (before other elements). The value of this element is specified as a parameter of this method. As a result, this method returns the number of elements in the array, taking into account the added one.

Var namePlanets = ["Mercury", "Earth", "Mars", "Jupiter"]; namePlanets.unshift("Venus"); // 5 console.log(namePlanets); // ["Venus", "Mercury", "Earth", "Mars", "Jupiter"]

The slice method (copying a section of an array)

The slice method is intended for copying a portion of an array. At the same time, it does not change the original array, but returns as a result a new array consisting of the selected elements.

The slice method has 2 parameters:

  • 1 parameter (mandatory) - used to specify the index of the element from which to start copying elements;
  • 2nd parameter (optional) - is intended to specify the index of the element to which it is necessary to copy (it is not included in the new array). If it is not specified, then the elements will be copied to the end of the specified array.
var namePlanets = ["Venus", "Mercury", "Earth", "Mars", "Jupiter"]; var newNamePlanets = namePlanets.slice(2, 4); // ["Earth", "Mars"]

splice method (changing the contents of an array)

The splice method is designed to change the contents of an array. It can be used both to add elements to an array and to remove them.

The syntax for the splice method is:

Array.splice(startIndex, deleteCount [, element1[, element2[, ...]]]); /* startIndex (required) - the starting index of the element from which to start modifying the array. If you specify a number greater than the length of the array as startIndex, then the start index will be set to the end of the array. If you specify a negative number as startIndex, then the starting element will be counted from the end. deleteCount (required) - a number indicating how many elements to remove from the array. If no elements are to be removed from the array, then deleteCount must be set to 0. After that, at least one new element must be specified to be added to the array. If you specify a number as deleteCount that will exceed the number of remaining elements in the array, starting from startIndex, then in this case they will still be deleted (i.e. all elements up to the end of the array, starting from the start index) element1, element2, . .. (optional) - elements to be added to the array. */

Examples of using the splice method.

Uses the splice method to remove a portion of elements from an array.

Var namePlanets = ["Venus", "Mercury", "Earth", "Mars"]; namePlanets.splice(2, 2); //["Earth", "Mars"] console.log(namePlanets); // ["Venus", "Mercury"]

Using the splice method to remove an element from an array and add new ones to it.

Var namePlanets = ["Venus", "Mercury", "Earth", "Mars"]; namePlanets.splice(1, 1, "Uranus", "Neptune", "Saturn"); // ["Mercury"] console.log(namePlanets); // ["Venus", "Uranus", "Neptune", "Saturn", "Earth", "Mars"]

Using the splice method only to add new elements to an array.

Var namePlanets = ["Jupiter", "Saturn", "Uranus"]; namePlanets.splice(0, 0, "Venus", "Mercury", "Earth", "Mars"); // console.log(namePlanets); // ["Venus", "Mercury", "Earth", "Mars", "Jupiter", "Saturn", "Uranus"]

join method (convert array to string)

The join method is designed to join all array elements into a string.

The syntax of the join method is:

Array.join(); /* separator (optional) - the separator that is used as a connecting string between each element of the array. If this parameter is not specified, "," will be used as the connecting string. If you specify an empty string as a parameter, then the array elements in the returned string will not be separated by anything */

Var berries = ["Grapes", "Grapes", "Currant", "Rosehip"]; var berriesStr1 = berries.join(); // "Grapes,Grapes,Currants, Rosehips" var berriesStr2 = berries.join(""); // "GrapesGrapesCurrantRosehip" var berriesStr3 = berries.join(", "); // "Grapes, Grapes, Currants, Rose hips" var berriesStr4 = berries.join(" + "); // "Grapes + Grapes + Currant + Rosehip"

If a separator is not a string, it will be converted to a string.

Var berries = ["Grapes", "Grapes", "Currant", "Rosehip"]; var berriesStr1 = berries.join(false); // "GrapesfalseGrapesfalseCurrantfalseRosehip" var berriesStr2 = berries.join(4/2); // "Grape2Grape2Currant2Rosehip" Array elements that have null or undefined as their value will be cast to an empty string. var arr = ; vararrStr = arr.join(", "); // "0, 5, -4"

Convert string to array - split

The split method is designed to convert a string to an array. This method has one parameter, for which you can specify a string, based on which this string will be split into an array of strings.

Var strElementComputers = "System unit, Monitor, Keyboard, Mouse, Speakers, Printer"; var elementComputers = strElementComputers.split(", "); console.log("Number of elements in the array: " + elementComputers.length); for (var i=0; i<= elementComputers.length-1; i++) { console.log(i + " элемент массива = " + elementComputers[i]); }

Reordering array elements in reverse order - reverse

The reverse method is for reordering array elements in reverse order.

Var namePlanets = new Array("Venus","Mercury","Earth","Mars"); namePlanets.reverse(); console.log("Number of elements in the array: " + namePlanets.length); for (var i=0; i<= namePlanets.length-1; i++) { console.log(i + " элемент массива = " + namePlanets[i]); }

Sorting array elements - sort

The sort method is for sorting the elements of an array. By default, this method sorts the array as strings.

Var namePlanets = new Array("Venus","Mercury","Earth","Mars"); namePlanets.sort(); console.log("Number of elements in the array: " + namePlanets.length); for (var i=0; i<= namePlanets.length-1; i++) { console.log(i + " элемент массива = " + namePlanets[i]); }

mob_info