Contacts

How to determine the length of the JavaScript array and many more functions of working with them. Sorting elements array - Sort

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

var Fruits \u003d ["Apple", "Orange", "donkey"]

To remove the item, place its index in square brackets. First index 0:

var Fruits \u003d ["Apple", "Orange", "donkey"] Alert (Fruits) Alert (Fruits) Alert (Fruits)

We can also get the length of the JavaScript array:

var Fruits \u003d ["Apple", "Orange", "donkey"] alert (fruits.length)

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

POP and PUSH methods

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

The following example shows how "donkey" is extracted from the array:

var Fruits \u003d ["Apple", "Orange", "donkey"] alert ("I delete" + fruits.pop ()) // Now we have only ["Apple", "Orange"] alert ("Now the size of the array : "+ fruits.length) // Donkel deleted

Please note that POP changes the array itself.

The POP analog is the PUSH method that adds an element into an array. For example, we forgot to add peach:

var Fruits \u003d ["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 " Classic.". You must have an array: " Jazz.”, ”Classic.”, ”Rock'n'ROLL". The code should work for any length of the array;
  4. Remove the last value from the array and output it via Alert.

Decision

// 1 var styles \u003d ["jazz", "Bluez"] // 2 styles.push ("Rock" n "roll") // or: styles \u003d "Rock" n "roll" // 3 styles \u003d "Classic "// 4 alert (styles.pop ())

SHIFT / UNSHIFT Methods

SHIFT / UNSHIFT methods work with the end of the array, but you can also use SHIFT to shift the elements up ( the first value of the array is removed with the shear of the elements). The UNSHIFT method allows you to add an item to an array from the end in JavaScript.

var Fruits \u003d ["Apple", "Orange"] var apple \u003d fruits.shift () // Now we have only ["Orange"] Fruits.unshift ("Lemon") // Now we have ["Lemon", "Orange"] alert (fruits.length) // 2

And SHIFT, and UNSHIFT can work with several elements at the same time:

var Fruits \u003d ["Apple"] fruits.push ("Orange", "peach") fruits.unshift ("Pineapple", "Lemon") // Now an array looks like this: ["Pineapple", "Lemon", "Apple "," Orange "," peach "]

Task for self-execution

Write the code to output through Alert a random value from the Arr array:

var arr \u003d ["plum", "orange", "donkey", "carrot", "javascript"]

Note: code to obtain a random number from the minimum to the maximum value (inclusive) the following:

var rand \u003d min + math.floor (math.random () * (max + 1-min))

Decision

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

var arr \u003d ["plum", "orange", "donkey", "carrot", "javascript"] var rand \u003d math.floor (math.random () * arr.length) alert (arr)

Bust Massiva

In JavaScript, the massif is performed using the for Cycle:

var fruits \u003d ["Pineapple", "Lemon", "Apple", "Orange", "peach"] for (var i \u003d 0; i

Task for self-execution

Create the Find (ARR, VALUE) function, which finds the value in a given array and returns its index or -1, if no value is found.

For example:

aRR \u003d ["TEST", 2, 1.5, FALSE] FIND (Arr, "Test") // 0 Find (Arr, 2) // 1 Find (ARR, 1.5) // 2 Find (Arr, 0) // -one

Decision

A possible solution may look like this:

fUNCTION FIND (for ARRAY, VALUE) (FOR (VAR i \u003d 0; I

But it is incorrect, because \u003d\u003d does not define the difference between 0 and false.

More correctly when working with arrays in JavaScript use \u003d\u003d\u003d. In addition, the latest ES5 standard contains the Array # indexof function. With it, we can determine the function as follows:

function Find (Array, Value) (IF (Array.indexof) Return Array.Indexof (Value) for (Var i \u003d 0; i

It would be more reasonable to determine the FIND via the condition to check if the IndexOF method exists.

Task for self-execution

Create Filternumeric (ARR), which accepts an array and returns a new array containing only numeric values \u200b\u200bfrom ARR.

An example of how it should work:

arr \u003d ["a", 1, "b", 2]; Arr \u003d Filternumeric (ARR); // now arr \u003d

Decision

The solution is to sort out an array and add values \u200b\u200bto a new array if they are numeric.

join and Split.

Sometimes you need a quick way to convert JavaScript an array into a string. This is where the Join method is intended.

It combines an array in the string using the specified separator:

var fruits \u003d ["lemon", "apple", "orange", "peach"]; var str \u003d fruits.join (","); Alert (STR);

The reverse conversion is easily performed using the SPLIT method:

var Fruits \u003d "Apple, Orange, Peach"; var arr \u003d fruits.split (","); // ARR contains now ["Apple", "Orange", "Peach"] Alert (ARR);

Task for self-execution

The object includes the ClassName property that contains the names of classes, separated by spaces:

Write the ADDCLASS feature (OBJ, CLS), which adds class CLS, but only if it does not exist:

dDCLASS (OBJ, "NEW") // obj.classname \u003d "Open Menu New" AddClass (OBJ, "Open") // No changes (OBJ, "ME") // obj.classname \u003d "Open Menu New Me" Alert (obj.classname) //

Decision

You need to divide the ClassName and the cycle on the part. If the class is not found, then it is added.

The cycle is slightly optimized to increase productivity:

fUNCTION AddClass (Elem, CLS) (for (var c \u003d elem.classname.split ("), i \u003d c.length-1; i\u003e \u003d 0; i--) (if (C [i] \u003d\u003d CLS ) Return) elem.classname + \u003d "" + CLS) var OBJ \u003d (Classname: "Open Menu") AddClass (OBJ, "NEW") AddClass (OBJ, Open ") Alert (obj.classname) // Open Menu new

In the example above, the variable C is determined at the beginning of the cycle, and the value i is set for its last index.

The cycle itself is processed in the opposite direction, ending with the condition I\u003e \u003d 0. Because I\u003e \u003d 0 Check faster than i. What the JavaScript accelerates the search in the array.

Using Length for cropping massif

Using the Length properties, you can cut an array as follows:

You specify the length, and the browser cuts up an array.

Array is an object that follows from this

In fact, JavaScript Array is an Object, supplemented by automatic length and special methods.

This differs from the concept in other languages, where arrays are a continuous memory segment. It also differs from the queue or stack based on related lists.

Non-key keys array

The keys are numbers, but they can have any names:

arr \u003d arr \u003d 5 arr.prop \u003d 10 // Do not do so

In JavaScript, arrays are hash tables with their advantages in terms of performance, but also with certain disadvantages.

For example, Push / POP work only with extreme elements of the array, so they are incredible quick.

push works only with the end:

var Arr \u003d ["My", "Array"] arr.push ("Something") Alert (ARR) // Row "Array"

SHIFT / UNSHIFT methods are slow, because they need to change the numbering of the entire array. The SPLICE method can also lead to a change in numbering:


Thus, SHIFT / UNSHIFT work more slowly than Push / Pop. The more array, the more time it takes in JavaScript sorting the array.

Task for self-execution

What is the result? Why?

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

Decision

Since arrays are objects, ARR .. in fact is a call to the object method, such as OBJ method.:

arr () // The same as arr () // syntax is incorrectly, but conceptually the same: arr.2 () // rewritten in the same style as OBJ.Method () this \u003d arr in this case The function is transmitted, so the contents of Arr are displayed. arr \u003d ["a", "b"] arr.push (function () (alert (this)) arr () // "a", "b", function

Rassdown arrays, description Length

The Length property allows you to get an array size in JavaScript, but the latest index + 1. This is important if we are talking about rarefied arrays, with "intervals" in indexes.

In the following example, we will add two elements into empty fruits, but the value of Length will remain 100:

var fruits \u003d // Empty array fruits \u003d "peach" fruits \u003d "apple" alert (fruits.length) // 100 (but elements in the array of only 2)

If you try to output a rarefied array, the browser will display the values \u200b\u200bof the missed indexes as empty items:

var Fruits \u003d // Empty array Fruits \u003d "peach" fruits \u003d "apple" alert (fruits) //, peach, apple (or something like this)

But an array is an object with two keys. Missing values \u200b\u200bdo not occupy space.

Rassded arrays behave bugly when the methods of the array are applied to them. They have no idea that the indices are missed:

var fruits \u003d fruits \u003d "peach" fruits \u003d "apple" alert (fruits.pop ()) // Pick up "Apple" (for index 9) alert (fruits.pop ()) // Pull out the not specified element (on the index 8 )

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

Removal from the massif

As we know, arrays are objects, so we could use Delete to remove the value:

var arr \u003d ["go", "to", "home"] delete arr // now arr \u003d ["go", undefined, "home"] alert (arr) // not specified

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

The Delete operator removes a key-value pair, and that's all. Naturally, since an array is only a hash, the position of the remote element becomes undefined.

Most often, we need to remove the element without leaving "holes" between indices. There is another method that will help us in this.

SPLICE method

The SPLICE method can delete elements and replace them in JavaScript multidimensional arrays. Its syntax:

arr.splice (Index, Deletecount [, Elem1, ..., Elemn])

Removes the DeleteCount item, starting with Index, and then inserts Elem1, ..., Elemn to its place.

Let's look at a few examples:

var arr \u003d ["go", "to", "home"] arr.splice (1, 1) // Delete 1 element, starting with an Alert index (arr.join (",")) // ["GO "," Home "] (1 element removed)

Thus, you can use Splice to remove one element from the array. The numbers of the elements of the array are shifted to fill the space:

var arr \u003d ["go", "to", "home"] arr.splice (0, 1) // Remove 1 element, starting with the index 0 Alert (Arr) // "To" became the first element

The following example shows how to replace items:

The Splice method returns an array of remote elements:

var arr \u003d ["go", "to", "home", "now"]; // Remove the first first element VAR removed \u003d 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 \u003d // 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

Task for self-execution

The object contains the ClassName property, which contains the names of the classes separated by spaces:

vAR OBJ \u003d (Classname: "Open Menu")

Write the RemoveClass feature (OBJ, CLS), which removes the CLS class if it is specified:

removeclass (OBJ, "Open") // obj.classname \u003d "MENU" Removeclass (OBJ, "BLABLA") // No change (class for removal does not exist)

Decision

You need to divide the classname to pieces and sort out these parts through the cycle. If the coincidence is found, it is removed from the JavaScript of the object array, and then added back to the end.

We optimize this:

function Removeclass (Elem, CLS) (for (var c \u003d elem.classname.split ("), i \u003d c.length-1; i\u003e \u003d 0; i--) (if (C [i] \u003d\u003d CLS ) c.splice (i, 1)) elem.classname \u003d c.join ("")) var OBJ \u003d (ClassName: "Open Menu") Removeclass (OBJ, "Open") Removeclass (OBJ, "BLABLA") Alert (obj.classname) // Menu

In the example above, the variable C is set at the beginning of the cycle, and for I is given to its last index.

The cycle itself is performed in the opposite direction, ending with the condition I\u003e \u003d 0. This is done because i\u003e \u003d 0 is checked faster than i. What speeds up searching properties in c.

Slice method

You can remove a part of the array using the SLICE method (Begin [, END]): var arr \u003d ["Why", "Learn", "javascript"]; var arr2 \u003d arr.slice (0.2) // takes 2 elements, starting with 0 alert (arr2.join (",")) // "Why, learn"

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

You can lower the second argument to get all the items starting from a specific index:

vAR ARR \u003d ["Why", "Learn", "javascript"]; Var Arr2 \u003d Arr.Slice (1) // Takes all items starting with 1 Alert (arr2.join (",")) // "Learn, JavaScript"

The method supports negative indices, just like String # Slice.

Reverse method

Another useful method is Reverse. Suppose I want to get the last part of the domain, for example, " com."From" my.Site.com.". That's how it can be done:

var domain \u003d "my.site.com" var last \u003d domain.split ("."). Reverse () Alert (Last)

Please note that JavaScript arrays support complex syntax (Reverse ()) to call the method, and then extract the element from the resulting array.

You can create longer calls, for example, Reverse () 0] Arr.Sort () Alert (Arr) // 1, 15, 2

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

Arrays

Array - This is an ordered collection of values. Values \u200b\u200bin array are called elements, and each element is characterized by a numerical position in an array called an index. JavaScript arrays are inepesed: the array elements may have any type, and different elements of the same array can have different types. The elements of the array may even be objects or other arrays, which allows you to create complex data structures, such as arrays of objects and array of arrays.

The countdown of arrays in the JavaScript language begins with scratch and 32-bit integers are used for them - the first element of the array has an index 0. Arrays in JavaScript are dynamic: they may increase and decrease in size as needed; There is no need to declare the fixed sizes of arrays when creating or re-distribute memory when the size changes.

JavaScript arrays are a specialized form of objects, and array indices mean a little more than just the names of the properties that coincide are integers.

Massive creation

It is easiest to create an array with the help of a literal that is a simple list of split elements of an array in square brackets. The values \u200b\u200bin the literal of the array do not have to be constants - it can be any expressions, including literals of objects:

Var empty \u003d; // Empty array VAR Numbers \u003d; // Array with five numeric elements VAR MISC \u003d [1.1, TRUE, "A",]; // 3 of the element of different types + final comma Var Base \u003d 1024; var table \u003d; // array with variables var arrobj \u003d [,]; // 2 array inside containing objects

The syntax of literal arrays allows you to insert an optional final comma, i.e. The literal [,] corresponds to the array with two elements, and not with three.

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

    Call a designer without arguments:

    Var arr \u003d new array ();

    In this case, an empty array will be created, an equivalent literary.

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

    Var Arr \u003d New Array (10);

    In this case, an empty array of said length will be created. This form of the constructor call array () can be used to pre-distribute memory for an array if the amount of its elements is known in advance. Please note that at the same time no values \u200b\u200bare saved in the array.

    It is clearly indicated in the constructor call the values \u200b\u200bof the first two or more elements of an array or one unlicas element:

    Var arr \u003d new array (5, 4, 3, 2, 1, "test");

    In this case, the constructor arguments become the values \u200b\u200bof the elements of the new array. The use of literal arrays is almost always easier than similar use of the Array () designer.

Reading and writing an array elements

Access to the elements of the array is carried out using the operator. To the left of the brackets should be the link to the array. Inside the brackets should be an arbitrary expression that returns non-negative meaning. This syntax is suitable for reading and recording the value of the array element. Consequently, all the following JavaScript instructions are allowed:

// Create an array with one element VAR ARR \u003d ["WORLD"]; // Read the element 0 var value \u003d arr; // Record the value in the element 1 Arr \u003d 3.14; // Record the value in the element 2 i \u003d 2; Arr [i] \u003d 3; // Record the value in the element 3 arr \u003d "hello"; // Read the elements 0 and 2, record the value in the element 3 ARR] \u003d ARR;

Let me remind you that arrays are a specialized variety of objects. Square brackets used to access the array elements act in the same way as square brackets used to access the properties of the object. The JavaScript interpreter converts numeric indexes specified in the brackets into the string - index 1 turns into a string "1" - and then uses strings as properties names.

There is nothing special in the conversion of numeric indexes in the line: the same can be done with conventional objects:

Var OBJ \u003d (); // Create a simple object OBJ \u003d "One"; // index it with integers

The feature of the arrays is that when using names of properties that are non-negative integers, arrays automatically determine the property value length.. For example, an array array with a single element was created above. Then the values \u200b\u200bof its elements with indexes 1, 2 and 3. As a result of these operations, the value of the Length properties of the array changed and became equal to 4.

It is necessary to clearly distinguish indexes in the array from the names of the properties of objects. All indexes are properties names, but only properties with names presented by integers are indexes. All arrays are objects, and you can add properties to them with any names. However, if you affect the properties that are array indexes, arrays respond to it, updating the value of the Length property if necessary.

Please note that negative and not numbers are allowed as array indices. In this case, the numbers are converted into strings that are used as properties.

Adding and removing array elements

We have already seen that the easiest way to add items to the array is to assign values \u200b\u200bto new indexes. To add one or more elements to the end of the array, you can also use the method push ():

Var arr \u003d; // Create an empty array arr.push ("zero"); // Add value to the end arr.push ("One", 2); // add two more values

Add an element to the end of the array can also, assigning the value to the ARR element. To insert an item to the beginning of the array, you can use the method unshift ()At the same time, the existing elements in the array are shifted in position with higher indices.

You can delete an array elements using the Delete statement as the usual properties of objects:

Var arr \u003d; Delete Arr; 2 in arr; // False, index 2 in the array is not defined by Arr.Length; // 3: The Delete operator does not change the LengTh property of the array

The removal of the element resembles (but is somewhat different) assigning the value undefined to this element. Please note that the application of the Delete statement to the array element does not change the value of the Length property and does not shift down the elements with higher indexes to fill the emptiness left after removing the item.

In addition, it is possible to remove elements in the end of the array by simply assigning the new value to the Length property. Arrays have a method pOP () (The opposite method Push ()), which reduces the length of the array by 1 and returns the value of the remote element. There is also a method shift () (The opposite method unshift ()), which removes the element at the beginning of the array. Unlike the Delete statement, the SHIFT () method shifts all the elements down to the position below their current indexes.

Finally there is a multi-purpose method sPLICE ()allowing you to insert, delete and replace the elements of arrays. It changes the value of the Length property and shifts an array elements with lower or high indices as needed. We will analyze all these methods a little later.

Multidimensional arrays

JavaScript does not support "real" multidimensional arrays, but it makes it easy to imitate them using arrays from arrays. To access the data item in an array of arrays, it is enough to use the operator twice.

For example, suppose that the MATRIX variable is an array of arrays of numbers. Each MATRIX [X] element is an array of numbers. To access a specific number in an array, you can use the expression MATRIX [X] [Y]. The following is a specific example, where the two-dimensional array is used as a multiplication table:

// Create a multidimensional array VAR Table \u003d New Array (10); // Table 10 strings FOR (var i \u003d 0; I

ARRAY class methods

ECMAScript 3 standard defines a lot of convenient features for working with arrays, which are available as methods of any array, as part of Array.Prototype. These methods will be presented in the following subsections.

Join ()

The array.join () method converts all the elements of the array in the string, combines them and returns the resulting string. In an optional argument, the method can be transferred to the string that will be used to separate items in the result string. If the separator string is not specified, the comma is used. For example, the following fragment gives a string "1,2,3":

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

Reverse ()

The array.reverse () method changes the order of the elements in the array to the opposite and returns a reordered array. The permutation is performed directly in the source array, i.e. This method does not create a new array with reordered elements, and reorders them in an existing array. For example, the following fragment where Reverse () and JOIN () methods are used, results in a string "3,2,1":

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

Sort () method

The array.sort () method sorts the elements in the source array and returns a sorted array. If the SORT () method is called without arguments, sorting is performed in alphabetical order (for comparison, items are temporarily converted into strings if necessary). Uncertain elements are transferred to the end of the array.

For sorting in any other order other than the alphabetic, Sort () method, you can transfer the comparison function as an argument. This feature sets which of its two arguments should follow before in the sorted list. If the first argument must precede the second, the comparison function must return a negative number. If the first argument should follow the second in the sorted array, the function must return the number greater than zero. And if two values \u200b\u200bare equivalent (i.e., the order of them is not important), the comparison function must return 0:

Var arr \u003d; arr.sort (); // Alphabetical order: 1111, 222, 33, 4 ARR.SORT (FUNCTION (A, B) (// Numeric order: 4, 33, 222, 1111 RETURN AB; // Returns a value of 0 // depending on the order of sorting a and b)); // we sort in the opposite direction, from more to less ARR.SORT (RETURN B-A));

Please note how convenient it is used in this fragment unnamed function. The comparison function is used only here, so there is no need to give her a name.

Concat () method

The array.concat () method creates and returns a new array containing the elements of the source array for which the Concat () method was called, and the values \u200b\u200bof all arguments transmitted by the Concat () method. If any of these arguments itself is an array, its elements are added to the returned array. However, it should be noted that the recursive transformation of the array of arrays into a one-dimensional array does not occur. The concat () method does not change the source array. Below are several examples:

Var arr \u003d; arr.concat (4, 5); // return arr.concat (); // Return Arr.Concat (,) // return arr.concat (4,]) // return]

Slice ()

The array.slice () method returns a fragment, or a submassion specified by the array. Two method arguments define the beginning and end of the returned fragment. The returned array contains an element whose number is indicated 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 specified, the returned array contains all elements from the initial position to the end of the array. If any of the arguments has a negative value, it defines the number of the element relative to the end of the array. So, the argument -1 corresponds to the last element of the array, and the argument -3 is the third element of the array from the end. Here are some examples:

Var arr \u003d; arr.slice (0.3); // return Arr.Slice (3); // return Arr.Slice (1, -1); // return arr.slice (-3, -2); // Robn

SPLICE ()

The array.splice () method is a universal method performing an insert or removal of an array elements. Unlike Slice () and Concat () methods, the SPLICE () method changes the source array relative to which it was called. Please note that Splice () and Slice () methods have very similar names, but perform completely different operations.

The SPLICE () method can delete elements from the array, insert new items or perform both operations at the same time. The elements of the array, if necessary, are displaced, continuous sequence after inserting or removal.

The first argument of the SPLICE () method determines the position in the array, starting with which the insert and / or removal will be performed. The second argument determines the number of elements that must be removed (cut) from the array. If the second argument is omitted, all the elements of the array are removed from the array specified to the end. The SPLICE () method returns an array of remote elements or (if none of the items have been removed) an empty array.

The first two arguments of the SPLICE () method () determine the elements of the array to be removed. For these arguments, any number of additional arguments that determine the elements that will be inserted into an array starting from the position indicated in the first argument.

Var arr \u003d; arr.splice (4); // return, arr \u003d arr.splice (1,2); // return, arr \u003d arr.splice (1,1); // returns; arr \u003d arr \u003d; arr.splice (2.0, "a", "b"); // returns; Arr \u003d.

Push () and POP () methods

Push () and pop () methods allow working with arrays as with stacks. The Push () method adds one or more new elements to the end of the array and returns it a new length. The POP () method performs a reverse operation - removes the last element of the array, reduces the length of the array and returns the value remand. Note that both of these methods change the source array, and do not create a modified copy.

UNSHIFT () and SHIFT () methods

UNSHIFT () and SHIFT () methods behave almost the same as Push () and POP (), except that they insert and remove the elements at the beginning of the array, and not at the end. The unshift () method displays the existing elements towards large indices to release the location, adds an element or elements to the beginning of the array and returns a new array length. The SHIFT () method deletes and returns the first element of the array, shifting all the subsequent elements to one position down to occupy the location released 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, as well as consider the main methods and properties available when working with them.

What is an array in javascript?

An array is ordered collection of values. Values \u200b\u200bin this collection are called elements. Each element in the array has its own sequence number (number), which is called the index. Indices are numbered 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).

Creation (announcement) array

Creating arrays in JavaScript is usually carried out using literals Massiva.

The literal of the array is square brackets, the inside of which is placed a list of elements separated by a comma.

For example:

Var empty \u003d; // Empty array VAR Numbers \u003d; // Numeric array VAR Arr \u003d; // An array containing various types of data

The values \u200b\u200bin the JavaScript array do not have to have the same type. Those. In one array, there may be values \u200b\u200bof various types of data.

Appeal to a specific array element is performed by its index. This operation is also called indexing operation.

For example:

// Create an array consisting of 3 elements of VAR SmartPhoneColors \u003d ["Black", "White", "Gray"]; // withdraw to the browser console Values \u200b\u200bof the SmartphoneColors array elements with indexes 0 and 2 Console.log ("The value of an array of SmartPhoneColors with an index 0:" + SmartPhoneColors); // "The value of the SmartPhoneColors array element with an index 0: black" Console.log ("The value of the SmartPhoneColors array element with an index 2:" + SmartPhoneColors); // "The value of an array of SmartPhoneColors with an index 0: grey" // Change the value of the SmartphoneColors array element with an index 1 to "Red" SmartPhoneColors \u003d "RED"; // ["black", "red", "grey"] // Set the smartphonecolors array element with an index 3 value "Blue" SmartPhoneColors \u003d "Blue"; // ["Black", "Red", "Gray", "Blue"]

As the values \u200b\u200bof the array elements, not only static values \u200b\u200bcan be used, but also expressions:

Var lengtha \u003d 7, widtha \u003d 5; var point \u003d;

Objects can be used as the values \u200b\u200bof the elements of the array.

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

Another way to create an array It is to call the Array constructor function.

Calling a designer function without arguments is used to create an empty array.

Var empty \u003d new array (); // Empty array

This method of creating an array, equivalent to the literal.

If the design function as an argument to specify the number, then it will create an array that will consist of a specified number of items. And all these elements will have as undefined value.

Var Arr \u003d New Array (5); // An array consisting of 5 elements (the values \u200b\u200bof the elements are undefined)

If the function-constructor in brackets transfer several values \u200b\u200bor one is not a numeric value, then it will create an array of arguments transmitted to it.

Unlike many other language programming languages, JavaScript automatically change its size, i.e. They are initially dynamic. Such arrays do not need to set any dimensions. Another distinctive feature of JavaScript arrays is that various elements of the same array may contain various data types.

Length property (array length)

The definition of the length of the array (number of elements) is carried out using the Length property.

// Create an array by transferring the values \u200b\u200bof the elements in the Array Var VolumeHDDDS \u003d New Array ("500GB", "1TB", "2TB"); // LengTharray variable Assign the length of the massif VolumeHDDS VAR LENGTHARRAY \u003d VOLUMEHDDS.LENGTH;

How to get the first element of the array

Obtaining the value of the first element of the array is carried out using the indication in the square brackets of this array of numbers 0:

// Creating an array consisting of 3 cells VAR VOLUMEHDDS \u003d NEW Array ("500GB", "1TB", "2TB"); // Obtaining the value of the first element of the VAR FIRSTVALUE \u003d VOLUMEHDDS array;

How to get the last element of the array

Obtaining the value of the last element of the array is carried out using the instructions in square brackets of this array of expression_name_LengTH-1:

// Creating an array consisting of 3 cells VAR VOLUMEHDDS \u003d NEW Array ("500GB", "1TB", "2tb"); // Get the value of the last element of the VAR LastValue \u003d VolumeHDDs array;

Bust Massiva

The brute force of the array elements is carried out using the FOR cycle.

For example, by moving all the elements of the array and bring their values \u200b\u200binto the browser console (F12):

// Creating a Namestudents array, consisting of 4 elements of Var Namestudents \u003d New Array ("Petya", "Vasya", "Kolya", "Maxim"); // BRAINING ELEMENTS OF THE MAS COLLECTED from 0 to the length of array-1 for (var i \u003d 0; I<= nameStudents.length-1; i++) { console.log(i+1 + " элемент массива = " + nameStudents[i]); }

For what is the delete operator

The Delete operator is not used to remove an element from an array, and to assign the resulting array to undefined.

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

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

An ARRAY object contains the following methods (functions) to work 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 indicated as the parameter of this method. As a result, the PUSH method returns the number of elements in the array taking into account the added.

Var nameplanets \u003d ["Venus", "Mercury", "Earth", "Mars"]; nameplanets.push ("Jupiter"); // 5 Console.log (Nameplanets); // ["Venus", "Mercury", "Earth", "Mars", "Jupiter"]

POP method (removal of the last element from the array)

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

Var nameplanets \u003d ["Venus", "Mercury", "Earth", "Mars"]; nameplanets.pop (); // "Mars" Console.log (Nameplanets); // ["Venus", "Mercury", "Earth"]

SHIFT method (removal of the first element from the 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. Each of them the index decreases by 1. This method as a result returns the value of the remote element.

Var nameplanets \u003d ["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 item to the beginning of the array (before other elements). The value of this element is indicated as the parameter of this method. As a result, this method returns the number of elements in the array taking into account the added.

Var nameplanets \u003d ["Mercury", "Earth", "Mars", "Jupiter"]; Nameplanets.unshift ("Venus"); // 5 Console.log (Nameplanets); // ["Venus", "Mercury", "Earth", "Mars", "Jupiter"]

Slice Method (Copying the Array section)

The SLICE method is designed to copy the area of \u200b\u200bthe array. At the same time, it does not change the original array, and returns a new array as a result consisting of selected items.

The Slice method has 2 parameters:

  • 1 parameter (required) - designed to specify an element index from which it is necessary to start copying elements;
  • 2 Parameter (optional) - designed to specify an element index to which it is necessary to copy (it does not turn on to a new array). If you do not specify it, the elements will be copied to the end of the specified array.
var nameplanets \u003d ["Venus", "Mercury", "Earth", "Mars", "Jupiter"]; var newnameplanets \u003d nameplanets.slice (2, 4); // ["Earth", "Mars"]

SPLICE method (Changing the contents of the array)

The SPLICE method is designed to change the contents of the array. It can be used both to add elements to an array, and for their removal.

SPLICE method syntax:

Array.splice (StartIndex, DeleteCount [, Element1 [, Element2 [, ...]]); / * StartIndex (required) - the starting index of the element from which to start changing the array. If you specify the number greater than the array length as StartIndex, the starting index will be installed at the end of the array. If you specify a negative number as StartIndex, then the starting element count will be done from the end. DELETECOUNT (required) - a number indicating how the number of items must be removed from the array. If items do not need to be removed from the array, the DeleteCount must be set 0. After that, you need to specify at least one new item you want to add to the array. If you specify the number as DeleteCount to exceed the number of remaining elements in the array, starting with StartIndex, then in this case they will still be deleted (i.e., all elements to the end of the array starting from the starting index) Element1, Element2 ,. .. (optional) - elements that need to be added to the array. * /

Examples of using the SPLICE method.

Applications of the SPLICE method to remove part of the elements from the array.

Var nameplanets \u003d ["Venus", "Mercury", "Earth", "Mars"]; nameplanets.splice (2, 2); // ["Earth", "Mars"] Console.log (Nameplanets); // ["Venus", "Mercury"]

Apply the SPLICE method to remove an element from the array and add new ones.

Var nameplanets \u003d ["Venus", "Mercury", "Earth", "Mars"]; nameplanets.splice (1, 1, "uranium", "Neptune", "Saturn"); // ["Mercury"] Console.log (Nameplanets); // ["Venus", "Uranus", "Neptune", "Saturn", "Earth", "Mars"]

Apply the SPLICE method only to add new elements to an array.

Var nameplanets \u003d ["Jupiter", "Saturn", "Uranus"]; nameplanets.splice (0, 0, "Venus", "Mercury", "Earth", "Mars"); // Console.log (Nameplanets); // ["Venus", "Mercury", "Earth", "Mars", "Jupiter", "Saturn", "Uranus"]

Join Method (array conversion in string)

The JOIN method is designed to connect all elements of the array in the string.

Join method syntax:

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

Var Berries \u003d ["Grapes", "Grapes", "Currant", "Rosehip"]; Var Berriesstr1 \u003d berries.join (); // "Grapes, grapes, currants, rosehip" Var Berriesstr2 \u003d berries.join ("); // "Vinongvinogradsmorrodinashpovik" Var Berriesstr3 \u003d berries.join (","); // "Grapes, grapes, currants, rosehip" Var Berriesstr4 \u003d berries.join ("+"); // "Grapes + grapes + currant + rosehip"

If you do not use a string as a separator, it will be converted to a string.

Var Berries \u003d ["Grapes", "Grapes", "Currant", "Rosehip"]; Var Berriesstr1 \u003d Berries.join (False); // "GrapefalSEVRogradFALSEMORODINAFALSSTR2 \u003d BERRIES.JOIN (4/2);" Var Berriesstr2 \u003d Berries.join // "Grapes2Vinograd2Smorodina2Withroduct" The elements of the array that have NULL or undefined will be shown to an empty string. var arr \u003d; var arrstr \u003d arr.join (","); // "0, 5, -4"

Row Conversion in Array - Split

The SPLIT method is designed to convert the string into an array. This method has one parameter, which you can specify a string on the basis of which this line will be divided into an array of rows.

Var streementcomputers \u003d "System block, monitor, keyboard, mouse, speakers, printer"; var elementcomputers \u003d strelementcomputers.split (","); Console.log ("The number of elements in the array:" + elementcomputers.length); for (var i \u003d 0; i<= elementComputers.length-1; i++) { console.log(i + " элемент массива = " + elementComputers[i]); }

Reordering the array elements in the reverse order - Reverse

The Reverse method is designed to reordering the elements of the array in the reverse order.

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

Sorting elements array - Sort

The SORT method is designed to sort the elements of the array. By default, this method sorts an array as strings.

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

And as you understand from that article, only one value can be saved into the variable. No matter how much we tried more than one value in the variable we will not write.

Suppose we will declare a certain variable Z, and assign it a value of 8. And if we are somewhere below in the code, then set the same variable, let's say 3, then the old value will disappear and the new value will be recorded and new.

And so in order for the variable to record more than one value, and you need to use this type of data as an array.

Array Allows you to write to the variable immediately an unlimited number of values, any types.

Previously, the JavaScript array was declared in this way:

Var arr \u003d new array (7, 8, "k", "v", 3.2, 4);

Times have changed and now the array is declared in a different way., More abbreviated. The elements are also listed through the comma, but already inside simple square brackets.

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

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

Each element from the array has its own index. Note that this index starts from scratch. With it, it is indicated by the position of the element in the array.

The structure of the array looks like that:

In order to contact 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, withdraw an element to the screen, in which the index is 2, that is, the letter "k".

Document.Write ("

We derive an element of array ARR, in which the index is equal to 2: "+ Arr +"

); // K.

What if we want see all elements of the array. If there are few elements, then you can contact 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 roll. It is already necessary to use here.

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

For interest, we learn how long the arrow array has.

Document.Write ("

The number of elements in the array Arr \u003d "+ Arr.Length +"

); // Result: 6

Now in order to bring all the elements at once, It is necessary to move the entire array using the cycle.

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

Array element ARR, with index "+ I +" Equal: "+ Arr [i] +"

"); }

Open this page in the browser and see such a picture:


For training, try to move the array of "Arr" and with the remaining cycles, while and do-while.

There is another simple and short exemption option. little 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 the list of elements in square brackets. Then we write the FEACH function and as a parameter we write alert method, without brackets.

Arr.Foreach (Alert);

Now if you open the page in the browser, we will see the alternately of each element of the array.

Filling an array with a cycle

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

First, it is necessary to declare an empty array, which we will fill. Then it is necessary to declare a variable and assign a value of 0 to it. This variable will be as an index for the declared array. And the next step will be the filling of the array using such a reception as a cycle into the cycle.

// We declare an empty array of var new_arr \u003d; // variable as an index for an array new_arr var k \u003d 0; for (var i \u003d 1; i

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


First, the variable i is equal to one. And this unit is multiplied with all values \u200b\u200bof the J. After 10 times went on the second cycle, we return to the first cycle and increment the variable I per unit. Now I is equal to two. Again we go to the second cycle and multiply the value 2 to all values \u200b\u200bof the variable J (from 1 to 10). As a result, the second row is obtained: 2 4 6 8 ... 20. And so it happens so far, the variable I will not be equal to 11. As soon as it takes such a value, then we leave the cycle.

Calculate the sum of all elements from the array

We have an array of new_arr in which 100 numbers are stored (a whole table of multiplication). Now let's consider the amount of all these elements.

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

The amount of the elements of the NEW_ARR array is equal to: "+ Summ +"

"); // Result 3025

That's all about what I wanted to tell you 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 found quite often, as they are very important in programming, so you must they know them perfectly.



Did you like the article? Share it