In this article we will look at JavaScript-array, its components.JavaScript is a perfectly-oriented scripting language, created for programming.In fact, he realizes language ECMAScript (ECMA-262 standard).
Where to use JavaScript?It is used as an embedded language in order to determine the path to the subject software application.It can be found in the browser: it is used there as a scripting language that gives interactivity to web pages.
important architectural features of this product are dynamic and weak typing, avtoupravlenie memory, ideal programming functions, which are the objects of the first category.
Actually, in JavaScript affected different reasons, because the development would create a language similar to Java, but easy to use by programmers.By the way, the JavaScript language does not own any company or organization that makes it different from a number of program styles used by web developers.
Note that JavaScript - a registered trademark of concern Oracle Corporation.
What is an array?
called Array data type that stores numbered values.Each such value is referred to as a component of the array, and the number to which a component is called the index.JavaScript-untyped array.This means that the details of the array can have whatever type, with various items belonging to the same array, have completely different styles.
addition, JavaScript-array is dynamic, and it is said that a fixed size there is no need to declare.After adding new parts at any time.
Manufacturing array
Using the language JavaScript, to create an array quite difficult.There are two methods for this.The first involves the production of an array using a literal - of square brackets, inside which is placed a list of items, divided by commas.
- var empty = [];// empty array;
- numers = var [4, 1, 2, 5];// array with five digital components;
- var diff = [1.5, false, «text"];// array with three elements of different types.
Typically, there is no requirement that the values were simple (and line number).It may also be any other expressions, for example, subject literals other functions and arrays.
second way to create an array of the designer is to call Array ().Invite him are three methods:
- Calling designer without arguments: var b - new Array ().It envisages the creation of an empty array equivalent literal empty [].
- Designer has clearly indicate the value of n components array: var b = new Array (1, 3, 5, 8, "a line», true).In this case, the designer presented a list of arguments, which are converted into the components of the new array.Arguments are written to the array is the location where indicated.
- Scoping for later assigning values.This is done by specifying the detection array of numbers enclosed in parentheses: var b = new Array (5).This method of detection involves the allocation of an array of the required number of components (each of which is listed as undefined) with the possibility of assigning values in the process of discussion.This form is typically used to pre-allocate the Javascript-array whose length is known in advance.
writing, reading and adding parts array
reach the components of the array, you can use the [] operator.Incidentally, all the components in JavaScript, starting with zero, numbered.To obtain the necessary elements, its number is indicated in brackets.As a rule, items can be changed.A JavaScript to add to the array, you need to assign a new value.
should be noted that in the JavaScript array can store any number of elements of any kind.
Length of
So we know what JavaScript.The length of the array in general is an interesting phenomenon.Let us consider it in more detail.All the ranges are designed by a designer Array (), and identified thanks to a literal array to have a specific property length, which recalls the total number of elements are preserved.Since the array may be uncertain of the details (denoted by undefined), a more accurate expression sounds so: Quality length is always greater by one than the largest number (index) component array.Quality length is adjusted automatically, staying accurate at occurrence in an array of new parts.
came to the final component of the array, you can use the feature length.
last item has an index is one less than the size of the array.After counting always start from scratch.Oh, this JavaScript!The length of the array it depends on the exact number of items.Therefore, if you do not know how much they should be, but you need to turn to the final element of the array, you need to apply the record: v.length - 1.
Bust parts array
Very often, the length property is used to iterate over the array of parts in the cycle:
- var fruits = [«Strawberry", "peach", "apple", "banana"];
- for (var I = 0; i & lt; fruits.lenght; i ++);
- document.write (fruits [i] + «...»).
In this example, it appears that components are placed continuously and begin with the first part, which owns the zero index.If not, before calling each element of the array should be checked, whether it is defined.
cycle is also sometimes used to initialize components.
Zoom and truncation array
wonder how using the JavaScript language in a string array to add?In the process of working with arrays, the length of the length automatically improves the quality, which is why we have to worry about it yourself.It is necessary to remember about one detail - the length property is not read-only is available, but for the record.If the length attribute to the quality of the value that gives the size of the current, then the array is reduced to a predetermined value.Any components that are not included in the new range of indices, recline, and their values are lost, even if later return back length - does not be restored.
very easy to clean because the array: foo.length = 0.
If the quality of run length greater than its current value at the end of the array will be new, unidentified items that will increase it to the desired size.
Removing parts array
delete operator specifies the component array to undefined, but it continues to exist in this case.If you must remove an item of JavaScript array so that the remaining parts were displaced for a seat, you must use one of the methods to predict the array.Method Array.shift () removes the first component, pop () - the final ingredient, and the method splice () - one or a range of components anywhere in the array.
Multidimensional Arrays
think we understand a little about what JavaScript.Two-dimensional arrays - that need to be addressed further.You remember that JavaScript arrays as components can contain other elements?This feature is used for the production of multi-dimensional arrays.To visit the ingredients in an array of arrays is sufficient to apply the brackets twice.
Associative arrays
Now, we learn how JavaScript trademark use associative arrays.To do this we need to look into the theory: associative arrays are sometimes called a hash table.Thanks to them, the indices used line.The use of such structures reminiscent of the use of the name of the properties of a simple object, but in this embodiment, when working in an array format.As in JavaScript there are no ways to operate associative arrays, they are used much less frequently than usual.It should be noted that they still can be useful for data storage and simplify storage of parts to which you want to access.
output array
And now we will study in the JavaScript?The output of the array to the dialog box (on the screen), and the output values of the components of the array.
If the program you want to display the values of all the components, then it is convenient to apply the instructions for.Interestingly, the variable-counter is used in the rules for this index component array.
Cleaning
To filter array of JavaScript, you need to reset the length:
- var myArray = [1, 2, 5, 23];
- myArray.length = 0.
following shows the implementation of destination clear (), in a JavaScript-framework, Prototype:
- clear: function () {;
- this.length = 0;
- return this;
- }.
Adding and removing components
Well, we continue to further explore this interesting language JavaScript.Array element and can be removed and added in the same manner as conventional properties of other objects.But there are some differences: while adding the numerical properties can change the quality of length, and the modification of the length property can be disposed of numerical quality.In principle, the algorithm setting qualities in such arrays is:
- When you add the unknown properties of digital i, if the length is equal to or less than i, length is determined to be i + 1,.
- When you change the quality of length are made as follows: if the assigned value is less than zero, then throws RangeError.Liquidated all numerical quality indexes that are equal to the new length, and greater than.
Generally remove the element of JavaScript array is easy.After all, even setting the length, it is necessary to remove from the "extra" components.Hence the cleaning option in the array.If the variable is assigned a new empty array for some reason, not satisfied, and it is necessary to reset the current, its quality is sufficient to assign a value of zero length.
methods unshift, shift, pop and push
Despite the fact that the components of the array are changed manually, many recommend this to apply built-in methods.It is this nuance guarantees the correct value the quality and the lack of length in the array passes.By the way, the correct length the quality will match the number of components.
push method moves to the end of the array passed to the details.Method pop gives back to the final component and removes it.
Generally in Internet Explorer under the eighth version unshift can return undefined, in other browsers - the new value of length.So on the return value from the unshift is better not to hope.
Adding and elimination of parts in the middle of the array
If you want to delete an array of JavaScript, you need to take?It is known that the method has a signature splice Array.prototype.splice.
He withdraws from the array deleteCount components, beginning with index start.If you transferred more than two arguments, all subsequent arguments are placed in the array instead of liquidated.If start is minus, the index from which to resume the withdrawal will be equal to the length + start.Returns an array of elements comes from the remote.
In fact, using the method splice, components can be removed from the middle of the array, or add any number anywhere in the array.
In the simplest case, if you need to remove a component with index i, have to request the array splice method with the parameters i and 1.
In principle, the second option at the splice method is not mandatory, but the behavior of one argument in each browser different.
For example, in Firefox, in the last variations of Opera, in Safari and in Chrome all the items will be withdrawn before the end of the array.
in IE will not liquidated any component.The first variation is impossible to predict the behavior of Opera - will be removed one piece with index start - 1. Therefore, you should always pass in the method at least two components.
Keys
course, learning JavaScript, associative arrays, as mentioned earlier, you must also not lose sight of.This is an abstract kind of information (the interface to the data store), which allows you to save pairs of the form "(key, value)" and add a pair of support operations, as well as delete and search for key pairs:
- FIND (key).
- INSERT (value, key).
- REMOVE (key).
It is believed that in the associative array unable to save two pairs with the same key.In a couple of k + vv called value associated with key k.Semantics and names above operations in various implementations of such arrays may be different.
Thus, the effect of FIND (key) returns the value associated with a given key, or a specific object UNDEF, which means that the value associated with a given key is missing.Two other actions do not return anything (except for the data that you have successfully executed this transaction).
Generally, from the point of view of the interface, which is an associative array considered as a simple array, wherein as indices can be applied not only to integers, and other types of values - for example, lines.
way, support for such arrays has many interpreted high-level programming languages such as PHP, Perl, Ruby, Python, Tcl, JavaScript, and others.For languages that have no built-in tools to work with associative arrays, created a huge number of implementations in the form of libraries.
example of an associative array can serve as a telephone directory.In this embodiment, the value of a set of "F.IO + e ", and the key - the telephone number.A phone number is one master, but one person can own several rooms.
Associated extension
should be noted that the most famous of expansion include the following:
- EACH - «go» to save all the pairs.
- CLEAR - to delete all the entries.
- MIN - find a pair with the lowest key.
- MAX - find the pair with the most crucial.
In the last two cases you need to on the keys indicated effects of comparison.
implementations of associative arrays
There are many different implementations of the associative array.The most common implementation may be based on a simple array whose components are the fumes (value key).To speed the search actions can be ordered on the components of the array and implement key finding by using a binary search.But it will increase the amount of time you need to add a new pair, as will need to "push" the components of the array that has appeared in an empty cell to pack a fresh record.
best known implementation, based on various search trees.For example, in a typical reading room STL of C ++ map container is realized on the basis of black and mahogany.In the style of Ruby, Tcl, Python used a type of hash table.There are also other implementation.
In general, each implementation has its advantages and disadvantages.It is important that all three operations were fulfilled on average, and in the worst period of nuance about (log n), where n - the current number to save par.For a concerted search trees (including black and red trees), this condition is satisfied.
known that implementations based on hash tables, defined as the average time O (1), which is better than the actions based on the search tree.Of course, this does not guarantee a high-speed execution of certain operations: the duration of the INSERT statement is referred to as the worst case O (n).INSERT process is performed for a long time when the duty ratio reaches the highest point, and there is the need to reconstruct the hash index table.
way, these statements hash bad that on this basis it is impossible to perform rapid additional action MAX, MIN and traversal algorithm to save all the pairs in order of decreasing or increasing keys.