In this article we will consider the JavaScript array, its components. JavaScript is an ideally-oriented scripting language created for programming. In fact, it implements the ECMAScript language (ECMA-262 standard).
Where is javascript used? It is used as an embedded language in order to determine the program path to the subject of the application. It can be found in browsers: it is used there as a scripting language that gives web pages interactivity.
The most important architectural features of this product are dynamic and weak typing, automatic memory management, perfect programming, functions that are objects of the first category.
In general, JavaScript was influenced by various reasons, because during development they wanted to create a language similar to Java, but easy for programmers to use. By the way, JavaScript is not spoken by any company or organization, which makes it unlike a number of programming styles used by web developers.
It should be noted that JavaScript is a registered trademark of Oracle Corporation.
What is an array?
An array is a data type that stores numbered values. Each such value is referred to as an array component, and the digit with which the component is associated is called an index. JavaScript array is untyped. This means that the details of the array can be of any type, and different parts belonging to the same array have completely different types.
In addition, the JavaScript array is dynamic, which means that there is no need to declare a fixed size. After all, you can add new parts at any time.
Array production
Using JavaScript, creating an array is not at all difficult. There are two methods for this. The first involves the manufacture of an array using a literal - square brackets, inside which a list of parts separated by commas is placed.
- var empty = []; // empty array;
- var numers = [4, 1, 2, 5]; // an array with five digital components;
- var diff = [1.5, false, "text"]; // array with three elements of different types.
As a rule, here it is not required that the values be simple (strings and numbers). It can also be any other expressions, for example, subject literals, other functions and arrays.
The second way to create an array is to call the designer Array (). You can invite him in three ways:
- Calling the designer without argument: var b - new Array (). It provides for the creation of an empty array equivalent to an empty literal [].
- The constructor explicitly has instructions for the value of the n components of the array: var b = new Array (1, 3, 5, 8, “string”, true). In this case, the designer is presented with a list of arguments that turn into components of the new array. Arguments are written to the array in the location in which they are specified.
- Definition of the area for subsequent assignment of values. This is done by indicating when identifying an array of one number, enclosed in parentheses: var b = new Array (5). This detection method involves allocating to the array the required number of components (each of which is listed as undefined) with the possibility of subsequent attribution of values in the process of presentation. This form is usually used to pre-place the Javascript array for which the length is known in advance.
Writing, reading and adding array details
You can get to the components of the array using the [] operator. By the way, all components in JavaScript, starting from scratch, are numbered. To obtain the necessary item, its number is indicated in square brackets. As a rule, details can be changed. And to add JavaScript to the array, assign a new enough value.
It should be noted that any number of elements of any kind can be stored in JavaScript arrays.
Array length
So, we know what JavaScript is. The length of the array is generally an interesting phenomenon. Let's consider it in more detail. All arrays, both constructed using the Array () designer, and identified through an array literal, have a specific length property that recalls the total number of elements to be saved. Since the array may contain undefined details (denoted by undefined), a more accurate expression sounds like this: the quality length is always one more than the largest number (index) of the array component. The length quality is adjusted automatically, remaining accurate when new parts appear in the array.
To make the final component of the array appear, you can use the length property.
The last part has an index one less than the size of the array. After all, the countdown always starts from scratch. Oh, this javascript! The length of its array depends on the exact number of elements. Therefore, if you do not know how many there should be, but you need to refer to the final element of the array, you need to apply the entry: v.length - 1.
Iterating over array details
Very often, the length property is used to iterate over the details of an array in a loop:
- var fruits = ["strawberry", "peach", "apple", "banana"];
- for (var I = 0; i <fruits.lenght; i ++);
- document.write (fruits [i] + "...").
In this example, it appears that the components are placed continuously and begin with the first part that has a zero index. If this is not the case, before calling each element of the array, it is necessary to check whether it is defined.
The loop is also sometimes used to initialize components.
Increase and truncate an array
I wonder how to use the JavaScript language to add a string to an array? In the process of working with arrays, the quality length length automatically improves, which is why we have to take care of this on our own. One detail needs to be remembered - the length property is not only readable, but also writable. If we attribute the quality length to a value that is inferior in size to the current one, then the array is reduced to a given value. Any components that are not included in the new range of indices are reclined, and their values are lost, even if you return length back later, the values are not restored.
It is quite simple to clear the array like this: foo.length = 0.
If the quality of length is performed greater than its current value, at the end of the array there will be new undefined parts that will increase it to the desired size.
Removing Array Parts
The delete operator indicates undefined in the array component, while it continues to exist. If you need to remove the element of the JavaScript array so that the remaining parts move to the free space, you need to use one of the predicted methods of the array. The Array.shift () method eliminates the first component, pop () the final component, and the splice () method eliminates one or a range of components anywhere in the array.
Multidimensional Arrays
We seem to have a little understanding of what JavaScript is. Two-dimensional arrays - that is what needs to be considered further. Do you remember that JavaScript arrays can contain other elements as components? This feature is used for the production of multidimensional arrays. To visit the components in an array of arrays, it is enough to apply square brackets twice.
Associative arrays
Now, let's examine how JavaScript's trademark associative arrays use. To do this, we need to look at the theory: associative arrays are sometimes called hash tables. Thanks to them, strings are used instead of indices. The use of such constructions resembles the use of the property name of a simple object, but in this case, when performing work in an array format. Since JavaScript does not have methods for handling associative arrays, they are used much less often than usual. It should be noted that they can still be useful for storing data and make it easier to remember details that need to be accessed.
Array output
What will we learn in JavaScript now? The output of the array in the dialog box (on the monitor screen), as well as the output of the values of the components of the array.
If the program needs to display the values of all components, then for this it is convenient to use the for statement. Interestingly, the for rule counter variable is used as an index to the array component.
Cleaning
In order to filter the JavaScript array, you need to reset its length:
- var myArray = [1, 2, 5, 23];
- myArray.length = 0.
The following shows the implementation of clear () assignment in the well-known Prototype JavaScript framework:
- clear: function () {;
- this.length = 0;
- return this;
- }.
Adding and Removing Components
Well, we continue to further study this interesting JavaScript language. An array element can be deleted and added in the same way as the usual properties of other objects. But there are some differences: when adding numerical properties, the quality of length can change, and when modifying the length property, numerical qualities can be eliminated. In principle, the quality setting algorithm for arrays is as follows:
- When adding an unknown digital property i, if length is equal to or less than i, length is determined to be i + 1.
- When changing the quality of length, the following actions are performed: if the assigned value is less than zero, then a RangeError is thrown. All numerical qualities and indices that are equal to the new length and which are greater are eliminated.
In general, removing an element of a JavaScript array is easy. After all, even setting length, you need to remove the "extra" components from it. From here follows the option of cleaning the array. If for some reason the assigned variable does not suit the empty new array, and it is necessary to reset the current one, it is enough to set its quality length to zero.
Unshift, shift, pop, and push methods
Despite the fact that the components of the array are changed manually, many recommend using built-in methods for this. It is this nuance that guarantees the correct value of the length quality and the absence of gaps in the array. By the way, the correct quality length will correspond to the number of components.
The push method transfers the transferred parts to the end of the array. The pop method returns the final component and removes it.
In general, in Internet Explorer under the eighth version, unshift can return undefined, in other browsers - a new length value. So it is better not to hope for the value returned from unshift.
Add and eliminate parts in the middle of an array
If you need to remove a JavaScript array, what should you do? The splice method is known to have the signature Array.prototype.splice.
It removes deleteCount components from the array, starting with the start metric. If more than two arguments are passed, then all subsequent arguments in the array are placed instead of the eliminated ones. If start is negative, then the index from which retrieval will resume will be equal to length + start. The return to the array comes from deleted elements.
In fact, using the splice method, you can remove components from the middle of the array or add any number to anywhere in the array.
In the simplest case, if you want to remove a component with index i, you need to request the splice method with parameters i and 1 from the array.
In principle, the second parameter of the splice method is optional, but the behavior of a function with one argument is different in each browser.
For example, in Firefox, in the latest versions of Opera, in Safari and in Chrome, all details will be removed to the end of the array.
In IE, not a single component will be eliminated. In the first variations of Opera, the behavior cannot be predicted - one part with the start index - 1 will be removed. Therefore, you must always pass at least two components to this method.
The keys
Of course, when learning JavaScript, associative arrays, as mentioned earlier, must also be kept in mind. This is an abstract type of information (interface to the data warehouse), which allows you to save pairs of the form “(key, value)” and support the operations of adding a pair, as well as deleting and searching for a pair by key:
- FIND (key).
- INSERT (value, key).
- REMOVE (key).
It is assumed that two pairs with similar keys cannot be saved in the associative array. In a pair, k + vv is called the quantity associated with the key k. The semantics and names of the above operations in different implementations of such arrays can be different.
So, the FIND action (key) returns the value associated with the given key, or some specific UNDEF object, meaning that the value associated with the given key is absent. The other two actions do not return anything (except for data on whether this operation was successfully completed).
In general, from the point of view of the interface, it is convenient to consider an associative array as a simple array, in which not only integers, but also values of other types can be used as indices - for example, strings.
By the way, support for such arrays is available in many interpreted high-level programming languages, such as PHP, Perl, Ruby, Python, Tcl, JavaScript and others. For languages that do not have built-in tools for working with associative arrays, a huge number of implementations in the form of libraries have been created.
An example of an associative array is a telephone directory. In this embodiment, the value is the complex “F. I.O. + address ”, and the key is the phone number. One telephone number has one owner, but one person can own several numbers.
Associative extensions
It should be noted that the most famous extensions include the following:
- EACH - “walk” through all saved pairs.
- CLEAR - delete all records.
- MIN - find the pair with the smallest key value.
- MAX - find the pair with the highest key value.
In the last two cases it is necessary that the action of comparison be indicated on the keys.
Associative Array Implementations
There are many different implementations of an associative array. The most common implementation can be based on a simple array whose components are pairs (value, key). To speed up the search actions, you can sort the components of this array by key and find using binary search. But this will increase the period of time needed to add a new pair, since it will be necessary to “push apart” the components of the array in order to pack a fresh record in the empty cell that appears.
The best known implementations are based on various search trees. For example, in a typical STL reader in C ++, the map container is implemented on the basis of black-red tree. In the styles of Ruby, Tcl, Python, one of the hash table types is used. There are other implementations.
In general, each implementation has its drawbacks and advantages. It is important that all three actions are performed both on average and in the worst nuance for the period O (log n), where n is the current number of pairs saved. For matched search trees (including black-red trees), this condition is satisfied.
It is known that in hash table based implementations, the average time is defined as O (1), which is better than in actions based on search trees. Of course, this does not guarantee the high-speed performance of individual operations: the INSERT action time in the worst case is denoted as O (n). The INSERT process takes a long time when the fill factor reaches its highest point and there is a need to reconstruct the hash table index.
By the way, these hash lists are bad in that they cannot be used to execute quick additional actions MAX, MIN and an algorithm for bypassing all saved pairs in descending or ascending order.