How to determine the length of a javascript array and many more functions for working with them. Removing from an 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.

What is an array in JavaScript?

An 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 starting from 0.

The following figure shows a numeric array consisting of 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 using array literal.

An array literal consists of square brackets containing a list of elements separated by a comma.

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.

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

For example:

// create an array consisting 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("Value of the smartphoneColors array element with index 0: " + smartphoneColors); // "The value of the smartphoneColors array element with index 0: Black" console.log("The value of the smartphoneColors array element with index 2: " + smartphoneColors); // "The value of the smartphoneColors array element with index 0: Gray" // change the value of the smartphoneColors array element with index 1 to "Red" smartphoneColors = "Red"; // ["Black", "Red", "Grey"] // set the smartphoneColors array element with index 3 to the value "Blue" smartphoneColors = "Blue"; // ["Black", "Red", "Grey", "Blue"]

You can use not only static values, but also expressions as array element values:

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 of calling the Array constructor function.

A constructor function call with no arguments is used to create an empty array.

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

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

If you specify a number as an argument to the constructor function, 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 consisting of 5 elements (element values ​​are undefined)

If you pass several values ​​or one non-numeric value 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 inherently dynamic. Such arrays do not need to be given any dimensions. Another distinctive 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 the array (number of elements) 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 through array elements 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("Petya","Vasya","Kolya","Maxim"); //iterate 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 used not to remove an element from an array, but to assign the value 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 (Array object methods)

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 the array)

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

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 an 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 an array)

The shift method is designed to remove the first element from the array, i.e. element having index 0. All other elements of the array are shifted to the beginning, i.e. for each of them the index is reduced 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 the array)

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

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

slice method (copying a section of an array)

The slice method is designed to copy a section of an array. However, 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 (required) - is intended to indicate the index of the element from which to start copying elements;
  • Parameter 2 (optional) - is intended to indicate the index of the element to which it is necessary to copy (in this case, it is not included in the new array). If you do not specify it, then elements up to the end of the specified array will be copied.
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 of the splice method is:

Array.splice(startIndex, deleteCount [, element1[, element2[, ...]]]); /* startIndex (required) - the starting index of the element from which to start changing 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 start element will be counted from the end. deleteCount (required) - a number indicating how many elements need to be deleted from the array. If elements do not need to be deleted from the array, then deleteCount must be set to 0. After this, you must specify at least one new element 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 to the end of the array, starting from the start index) element1, element2, . .. (optional) - elements that need to be added to the array. */

Examples of using the splice method.

Using the splice method to remove some 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 (converting an array to a string)

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

Join method syntax:

Array.join(); /* separator (optional) - a separator that is used as a connecting string between each array element. 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", "Rose Hip"]; var berriesStr1 = berries.join(); // "Grapes, Grapes, Currants, Rose Hips" var berriesStr2 = berries.join(""); // "GrapesGrapesCurrantRosehip" var berriesStr3 = berries.join(", "); // "Grapes, Grapes, Currants, Rosehips" var berriesStr4 = berries.join(" + "); // "Grapes + Grapes + Currants + Rose Hips"

If you use a non-string as a separator, it will be converted to a string.

Var berries = ["Grapes", "Grapes", "Currant", "Rose Hip"]; var berriesStr1 = berries.join(false); // "GrapesfalseGrapesfalseCurrantfalseRosehip" var berriesStr2 = berries.join(4/2); // "Grapes2Grapes2Currant2Rose Hip" Array elements that have null or undefined as a value will be cast to the empty string. var arr = ; var arrStr = arr.join(", "); // "0, 5, -4"

Converting a string to an array - split

The split method is designed to convert a string into an array. This method has one parameter, as which you can specify a string, based on which this string will be divided 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 designed to reorder 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 used to sort array elements. 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]); }

06/21/2017 at 12:17

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 missing indexes. For example

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

The length property returns the maximum index of the array + 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 regular objects, so calculating the size of an array in bytes is no different than calculating the size of any other object. Unfortunately, javascript does not provide an API for calculating the size, so you will have to calculate it yourself. This is done as follows: we go through 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 overall 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, there is a possibility of going into an endless 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.

Initializing an Array

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

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

You can immediately initialize an array with a certain 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 add new elements to it as you go:

Var users = 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. Using indexes, we can substitute one or another element in an array at a specific index.

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 the 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:

Var users = new Array(); // there are 0 elements in the array users = "Tom"; users = "Kate"; users = "Sam"; for(var i=0; i

Browser output:

Tom Kate undefined undefined Sam

Despite the fact that we did not add elements for indices 2 and 3, the length of the array in this case will be the number 5. It’s just that elements with indices 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 a variable the value of another variable that stores an array:

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

In this case, the people variable, after copying, 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 it 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 using 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.

The slice() method also 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 the starting and ending indexes, which are used to retrieve 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 elements.

push()

The push() method adds an element to the end of the 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(); // extract the last element from the array document.write(lastFruit + "
"); document.write("In the array fruit " + fruit.length + " element:
"); for(var i=0; i ");

Browser output:

Plums The 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 the array fruit " + fruit.length + " element:
"); for(var i=0; i ");

Browser output:

Apples The 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 at 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 occurs from the beginning of the array. If you pass a negative index, then the deletion 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 ending index for deletion. For example, let's delete 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 instead of deleted 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 delete three elements from the 1st to 3rd indices and insert two elements instead.

concat()

The concat() method is used to combine 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. Various types are possible:

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

join()

The join() method joins all the elements of an array into one string:

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

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

sort()

The sort() method sorts the 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] + "
");

Browser output:

Apricots pears peaches plums apples

reverse()

The reverse() method reverses the array backwards:

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

Browser output:

Peaches apricots plums pears apples

In combination with the sort() method, you can sort the 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] + "
");

Browser output:

Apples plums peaches pears apricots

Finding an element's index

The indexOf() and lastIndexOf() methods return the index of the first and last inclusion of an element in the 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 has a value of 0 because the first inclusion of the "apples" line in the array is at index 0, and the last is at index 3.

If the element is not in the array, then in this case the indexOf() and lastIndexOf() methods return the value -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 representing 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 element value for compliance with some condition. For example, in this example we check 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 meets the condition. If less, then return false - the element does not meet the condition.

As a result, when the numbers.every(condition) method is called, it iterates through all the elements of the numbers array and passes them one by one to the condition function. If this function returns true for all elements, then the every() method 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 whether at least one element matches a condition. And in this case, the some() method returns true . If there are no elements matching the condition in the array, 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() , accepts 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] + "
");

Browser output:

1 8 25 42

forEach() and map()

The forEach() and map() methods iterate over 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, into which, when iterating over elements, the current element being iterated is passed 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 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 use the map method to calculate the squares of 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 receives the current element being iterated, performs operations on it and returns some value. This value then goes into the resulting squareArray

In this article we will look at standard JavaScript arrays with numeric indexes. Arrays are declared using square brackets:

var fruits = ["Apple", "Orange", "Donkey"]

To extract an element, place its index in square brackets. First index 0 :

var fruits = ["Apple", "Orange", "Donkey"] alert(fruits) alert(fruits) alert(fruits)

We can also get the length of a JavaScript array:

var fruits = ["Apple", "Orange", "Donkey"] alert(fruits.length)

Oops! We created an array with two fruits and a donkey. Now we need to remove the donkey.

pop and push methods

The pop method in JavaScript removes an element from an array and returns it.

The following example shows how "Donkey" is retrieved from an array:

var fruits = ["Apple", "Orange", "Donkey"] alert("I'm removing "+fruits.pop()) // Now we only have ["Apple","Orange"] alert("Now the size of the array : "+fruits.length) // donkey removed

Note that pop modifies the array itself.

Pop's counterpart is the push method, which adds an element to an array. For example, we forgot to add a peach:

var fruits = ["Apple", "Orange"] fruits.push("Peach"); // now we have ["Apple", "Orange", "Peach"] alert("Last element:"+fruits)

  1. Create an array of styles with elements “ Jazz”, “Blues”;
  2. Add the value " Rock'n'Roll«;
  3. Replace the second value from the end with the value " Classic". You should end up with an array: “ Jazz”, ”Classic”, ”Rock'n'Roll" The code should work for any array length;
  4. Retrieve the last value from the array and display it via alert .

Solution

// 1 var styles = ["Jazz", "Bluez"] // 2 styles.push("Rock"n"Roll") // or: styles = "Rock"n"Roll" // 3 styles = "Classic " // 4 alert(styles.pop())

Shift/unshift methods

The shift/unshift methods work on the end of the array, but you can also use shift to shift elements up ( the first value of the array is removed by shifting the elements). The unshift method allows JavaScript to add an element to an array from the end:

var fruits = ["Apple", "Orange"] var apple = fruits.shift() // now we only have ["Orange"] fruits.unshift("Lemon") // now we have ["Lemon", "Orange"] alert(fruits.length) // 2

Both shift and unshift can operate on multiple elements at once:

var fruits = ["Apple"] fruits.push("Orange","Peach") fruits.unshift("Pineapple","Lemon") // now the array looks like this: ["Pineapple", "Lemon", "Apple" ", "Orange", "Peach"]

Self-administered task

Write the code to display a random value from the arr array via alert:

var arr = ["Plum","Orange","Donkey","Carrot","JavaScript"]

Note: The code to get a random number from the minimum to the maximum value (inclusive) is as follows:

var rand = min + Math.floor(Math.random()*(max+1-min))

Solution

We need to extract a random number from 0 to arr.length-1 (inclusive):

var arr = ["Plum","Orange","Donkey","Carrot","JavaScript"] var rand = Math.floor(Math.random()*arr.length) alert(arr)

Iterating over an array

In JavaScript, iterating through an array is done using a for loop:

var fruits = ["Pineapple", "Lemon", "Apple", "Orange", "Peach"] for(var i=0; i

Self-administered task

Create a function find(arr,value) that finds a value in a given array and returns its index or -1 if the value is not found.

For example:

arr = [ "test", 2, 1.5, false ] find(arr, "test") // 0 find(arr, 2) // 1 find(arr, 1.5) // 2 find(arr, 0) // -1

Solution

A possible solution might look like this:

function find(array, value) ( ​​for(var i=0; i

But this is incorrect because == does not define the difference between 0 and false .

It is more correct to use === when working with arrays in JavaScript. Additionally, the latest ES5 standard includes the Array#indexOf function. With it, we can define a function like this:

function find(array, value) ( ​​if (array.indexOf) return array.indexOf(value) for(var i=0; i

Even smarter would be to define find with a condition to check if the indexOf method exists.

Self-administered task

Create a function filterNumeric(arr) that takes an array and returns a new array containing only the numeric values ​​from arr .

An example of how this should work:

arr = ["a", 1, "b", 2]; arr = filterNumeric(arr); // now arr =

Solution

The solution is to iterate through the array and add the values ​​to a new array if they are numeric.

join and split

Sometimes you need a quick way to convert a JavaScript array to a string. This is what the join method is for.

It concatenates the array into a string using the given delimiter:

var fruits = ["Lemon","Apple","Orange","Peach"]; var str = fruits.join(", "); alert(str);

The reverse conversion is easily done using the split method:

var fruits = "Apple,Orange,Peach"; var arr = fruits.split(","); // arr now contains ["Apple", "Orange", "Peach"] alert(arr);

Self-administered task

The object includes a className property, which contains the class names, separated by spaces:

Write a function addClass(obj, cls) that adds the class cls , but only if it doesn't exist:

ddClass(obj, "new") // obj.className="open menu new" addClass(obj, "open") // no changes (class already exists) addClass(obj, "me") // obj.className= "open menu new me" alert(obj.className) //

Solution

You need to split the className and the loop into parts. If the class is not found, then it is added.

The loop has been slightly optimized to increase performance:

function addClass(elem, cls) ( for(var c = elem.className.split(" "), i=c.length-1; i>=0; i--) ( if (c[i] == cls ) return ) elem.className += " "+cls ) var obj = ( className: "open menu" ) addClass(obj, "new") addClass(obj, "open") alert(obj.className) // open menu new

In the example above, the variable c is defined at the beginning of the loop and its last index is set to i .

The loop itself is processed in the opposite direction, ending with the condition i>=0. Because i>=0 is faster to check than i . What in JavaScript speeds up searching in an array.

Using length to trim an array

Using the length property, you can truncate an array like this:

You specify the length and the browser truncates the array.

Array is an object, so what does this mean?

In fact, in JavaScript, an Array is an Object, complete with automatic length setting and special methods.

This is different from the concept in other languages, where arrays represent a contiguous segment of memory. This is also different from a queue or stack based on linked lists.

Non-numeric array keys

Keys are numbers, but they can have any name:

arr = arr = 5 arr.prop = 10 // don't do this

In JavaScript, arrays are hash tables, which have performance advantages but also certain disadvantages.

For example, push/pop only works on the outermost elements of an array, so they are incredibly fast.

push only works with the end:

var arr = ["My", "array"] arr.push("something") alert(arr) // string "array"

The shift/unshift methods are slow because they need to renumber the entire array. The splice method can also cause the numbering to change:


So shift/unshift are slower than push/pop . The larger the array, the longer it takes JavaScript to sort the array.

Self-administered task

What will be the result? Why?

arr = ["a", "b"] arr.push(function() ( alert(this) )) arr() // ?

Solution

Since arrays are objects, arr .. is actually a method call on an object such as obj method:

arr() // same as arr() // syntactically incorrect, but conceptually the same: arr.2() // rewritten in the same style as obj.method() this = arr in this case is passed to the function, so the contents of arr are printed. arr = ["a", "b"] arr.push(function() ( alert(this) )) arr() // "a","b",function

Sparse arrays, length description

The length property allows you to get not the size of an array in JavaScript, but the last index + 1. This is important when we are talking about sparse arrays, with “gaps” in the indices.

In the following example, we will add two elements to the empty fruits , but the length value will remain 100 :

var fruits = // empty array fruits = "Peach" fruits = "Apple" alert(fruits.length) // 100 (but there are only 2 elements in the array)

If you try to output a sparse array, the browser will return the missing index values ​​as empty elements:

var fruits = // empty array fruits = "Peach" fruits = "Apple" alert(fruits) // ,Peach,Apple (or something like that)

But an array is an object with two keys. Missing values ​​do not take up space.

Sparse arrays behave weirdly when array methods are applied to them. They have no idea that indexes are missing:

var fruits = fruits = "Peach" fruits = "Apple" alert(fruits.pop()) // pop "Apple" (to index 9) alert(fruits.pop()) // pop an unspecified element (to index 8 )

Try to avoid sparse arrays. In any case, their methods will not work normally. Use Object instead.

Removing from an array

As we know, arrays are objects, so we could use delete to remove a value:

var arr = ["Go", "to", "home"] delete arr // now arr = ["Go", undefined, "home"] alert(arr) // not defined

You can see that the value is removed, but not in the way we would like, because the array contains an unspecified element.

The delete operator removes a key-value pair and that's it. Naturally, since the array is only a hash, the position of the removed element becomes undefined.

Most often we need to remove an element without leaving “holes” between the indices. There is another method that will help us with this.

splice method

The splice method can remove elements and replace them in JavaScript multidimensional arrays. Its syntax is:

arr.splice(index, deleteCount[, elem1, ..., elemN])

Removes the deleteCount element starting at index and then inserts elem1, ..., elemN in its place.

Let's look at a few examples:

var arr = ["Go", "to", "home"] arr.splice(1, 1) // remove 1 element starting at index 1 alert(arr.join(",")) // ["Go ", "home"] (1 element removed)

So you can use splice to remove one element from an array. The array element numbers are shifted to fill the space:

var arr = ["Go", "to", "home"] arr.splice(0, 1) // remove 1 element, starting from index 0 alert(arr) // "to" became the first element

The following example shows how to replace elements:

The splice method returns an array of removed elements:

var arr = ["Go", "to", "home", "now"]; // remove the first 2 elements var removed = arr.splice(0, 2) alert(removed) // "Go", "to"<-- массив удаленных элементов splice может вставлять элементы, задайте 0 для deleteCount. var arr = ["Go", "to", "home"]; // со второй позиции // удаляем 0 // и вставляем "my", "sweet" arr.splice(2, 0, "my", "sweet") alert(arr) // "Go", "to", "my", "sweet", "home"

This method can also use a negative index, which is counted from the end of the array:

var arr = // for element -1 (penultimate) // remove 0 elements, // and insert 3 and 4 arr.splice(-1, 0, 3, 4) alert(arr) // 1,2,3, 4.5

Self-administered task

The object contains a className property, which contains the class names, separated by spaces:

var obj = (className: "open menu")

Write a function removeClass(obj, cls) that removes the class cls if it is given:

removeClass(obj, "open") // obj.className="menu" removeClass(obj, "blabla") // no changes (there is no class to remove)

Solution

You need to split the className into parts and loop through these parts. If a match is found, it is removed from the JavaScript array of objects and then added back to the end.

Let's optimize this a little:

function removeClass(elem, cls) ( for(var c = elem.className.split(" "), i=c.length-1; i>=0; i--) ( if (c[i] == cls ) c.splice(i,1) ) elem.className = c.join(" ") ) var obj = ( className: "open menu" ) removeClass(obj, "open") removeClass(obj, "blabla") alert (obj.className) // menu

In the above example, the variable c is set at the beginning of the loop and i is set to its last index.

The loop itself runs in the opposite direction, ending with the condition i>=0. This is done because i>=0 is checked faster than i . Which speeds up searching for properties in c .

slice method

You can extract part of an array using the slice(begin[, end]) method: var arr = ["Why", "learn", "JavaScript"]; var arr2 = arr.slice(0,2) // takes 2 elements, starting at 0 alert(arr2.join(", ")) // "Why, learn"

Please note that this method does not change the number of elements in the array in JavaScript, but copies part of it.

You can omit the second argument to get all elements starting at a specific index:

var arr = ["Why", "learn", "JavaScript"]; var arr2 = arr.slice(1) // takes all elements starting from 1 alert(arr2.join(", ")) // "learn, JavaScript"

The method supports negative indexes, just like String#slice .

reverse method

Another useful method is reverse . Let's say I want to get the last part of a domain like " com” from “ my.site.com" Here's how to do it:

var domain = "my.site.com" var last = domain.split(".").reverse() alert(last)

Note that JavaScript arrays support a complex syntax (reverse()) for calling a method and then retrieving an element from the resulting array.

You can create longer calls like reverse() 0] arr.sort() alert(arr) // 1, 15, 2

Run the above code. You will get the order 1, 15, 2. This is because the method converts everything to a string and uses lexicographic order by default.