JavaScript Learning--ITEM30 Array Advanced Full Mastery

Source: Internet
Author: User
Tags array length terminates

The importance of arrays in programming languages is self-evident, and JavaScript arrays are one of the most commonly used objects, arrays are an ordered set of values, and because of the weak type, arrays in JavaScript are very flexible and powerful. Unlike a strongly typed high-level language array such as Java, which can hold only the same type or its subtype elements, JavaScript is able to hold multiple types of elements in the same group, and the length can be dynamically adjusted, making changes to the automatic array length as the data increases or decreases.

1. Creating an array

Creating arrays in JavaScript in many ways

1. Constructor function

1. No parameter constructor, create an empty array

var a1=New Array ();

2. A numeric parameter constructor that specifies the length of the array (due to the fact that the array length can be dynamically adjusted and not large) to create an array of the specified length

var a2=New Array (5);

3. Constructor with initialization data, create array and initialize parameter data

var a3=New Array (4, ' Hello ',new Date ());

2. Literal quantity

1. Use square brackets to create an empty array, equivalent to calling the parameterless constructor

var a4=[];

2. Use the brackets and pass in the initialization data, equivalent to calling the constructor with the initialized data

var a5=[10];

Watch out.

1. If you pass in a numeric parameter when creating an array using a constructor, an array of length parameters is created, and if more than one is passed, an array is created, and the parameters are added to the array as initialization data

var a1=New Array (5);   Console.log (a1.length); // 5   // [], the array is empty   var a2=New Array (5,6);   Console.log (a2.length); // 2   // [5,6]

However, using the literal method, the parameters are treated as initialization content, regardless of the number of arguments passed in.

var a1=[5];   Console.log (a1.length); // 1   // [5]   var a2=[5,6];   Console.log (a2.length); // 2   // [5,6]

2. When creating an array using the initialization parameters, it is best not to take the extra "," in different browsers to handle this differently

var a1=[1,2,3,];console.log (a1.length); Console.log (A1);

This script runs on a modern browser as we imagine, the length is 3, but in the low version of IE, the length is 4 of the array, the last data is undefined

2. Index and length of array

The value of an array can be read and written by natural number index access, or it can be a variable or expression that results in a nonnegative integer

var a1=[1,2,3,4];console.log (a1[//1var i=1//2  //3

Arrays are also objects, and the secret to using an index is that the array converts the index value to the corresponding string (1=> "1") as the object property name

 in A1); // true, is indeed a property

the index is unique in that the array automatically updates the Length property, although the JavaScript syntax specifies that the number cannot be used as a variable name, so we cannot display a format that uses array.1. This shows that negative numbers, even non-numeric "indexes" are allowed, except that these become arrays of properties, not indexes

var a=New Array,a[-10]= "a[-10",a["sss"]= "SSS";

so we can see that all the indexes are property names, but only the natural number (with the maximum) is the index, generally we do not have an array out of bounds when using the array error is precisely because of this, The index of an array can be not contiguous, and returns undefined when accessing an element that does not exist on index

var a=New Array (+/-);   a[100]=100;    // 101   // undefined   // undefined   Console.log (a[100]); 100

In the above example, although the direct a[100] assignment does not affect a[4] or a[99], but the length of the array is affected, the array is equal to the maximum number of index+1 in the array, we know that the length property of the array is also a writable property, When you force the value of the length property of an array to be less than or equal to the maximum index value, the array automatically deletes data with indexd greater than or equal to length, appending a few sentences in the code just now

a.length=2Console.log (a); // [up]

A[2] and a[100] are automatically deleted, so if you set the length to a value greater than the maximum index+1, the array will expand automatically, but no new elements will be added to the arrays, just append empty space at the tail

A.length=5//[up]//No 3 undefined behind
3. Element additions/Deletions

1. Basic methods

The above example has been used to add element methods to the array, directly using the index can be (index not necessary continuous)

var a=New Array,a[3]=4; Console.log (a); // [1, 2, 3, 4]

as mentioned earlier, arrays are also objects, indexes are only special properties , so we can use Delete to delete an array element using the method of deleting the object property

Delete a[2];console.log (a[//undefined

this is similar to assigning a[2] to undefined, does not change the array length And does not change the index and value correspondence of other data

2. Stack method

The above example is always found by students, especially its deletion method, is not the form of our hope, many times we want to delete the intermediate element, the index of the subsequent element automatically minus one, the array length minus one, as if in a stack to take the one, Arrays have helped us do this, pop and push allows us to use the stack as a first-in and out-of-use array

var a=New Array (+/-);   A.push (4);   Console.log (a); //    Console.log (a.length);   4   Console.log (A.pop (a));   4   //   console.log (a.length);   3

3. Queue method

Since the stack method is implemented, first-in-first-out queue how little, the shift method can delete the array index minimum element, and the subsequent element index minus one, length also minus one, so use Shift/push can simulate the queue.

Using the shift () and push () methods together, you can use arrays as you would with queues:

var colors=new Array ();

var Count=colors.push ("Red", "green"); Push in two items

alert (count); 2

Count= Colors.push ("Black"); Add an item from the end of the array, at which point the order of the array is: "Red", "green", "black"

alert (count); 3

var item=colors.shift (); Get the first item

alert (item); "Red"

alert (colors.length); 2

As you can see from the example, the shift () and push () methods can add items from the end of the array, move the first item in the group, and return the item.

If you want to do the opposite, you can use the Unshift () and Pop () methods, which are to add items to the front end of the array and remove items from the end of the array.

var colors=new Array ();

var count=colors.unshift ("Red", "green");//push in two

alert (count); 2

Count=colors.unshift ("Black"); Add items from the front of the array, at which point the order of the array is: "Black", "red", "green"

alert (count); 3

var item=colors.pop ();

alert (item); Remove and return the last item "green"

From the above two sets of examples, we can clearly see the use of these two sets of methods.

4. Ultimate Artifact

JavaScript provides a splice method for one-time solution to array additions, deletions (these two methods combine to achieve the substitution effect), the method has three parameters

1. Start indexing

2. Removing the displacement of an element

3. Insert a new element, of course, can also write multiple

The Splice method returns a new array consisting of the deleted elements, and returns an empty array without deleting the

var a=New Array (1,2,3,4,5);


Specify the first two parameters, you can use splice to delete the array elements, also bring index adjustment and length adjustment

var a=New Array (1,2,3,4,5); Console.log (A.splice (1,3)); //  Console.log (a.length); // 2Console.log (a); // [1,5]

If the array index is not starting from 0, then the result will be interesting, with an array like this

var a=New  Array ();        a[2]=2;        a[3]=3;        a[7]=4;        a[8]=5;

// 5//[2:2, 3:4, 4:5]  

As you can see from the example above, the first parameter of splice is Absolute index value, not relative to the array index , the second parameter is not the number of deleted elements, but the number of times to delete the action, not by the actual index of the array to move, but continuous movement. Adjust The index of the trailing element at the same time, ignoring the previous index

Insert and replace

As long as the second parameter of the method, that is, the deletion action is set to 0, the third parameter and later fill in the content to insert the splice can perform the insert operation, and if the second parameter is not 0 becomes the first to remove the insertion, that is, the replacement effect

var a=New Array (1,2,3,4,5);   A.splice (1,0,9,99,999);    // 8   Console.log (a); //    a.splice (1,3,8,88,888);   Console.log (a.length); // 8   Console.log (a); // [1, 8, 888, 2, 3, 4, 5]
4. Common Methods

Join (Char)

This method is also used in languages such as C # to concatenate array elements (objects called their ToString () methods) into a string using parameters as connectors

var a=New Array (1,2,3,4,5);       Console.log (A.join (////       1 2 3 4 5

Slice (start,end)

Do not confuse with the splice method, slice

var a=New Array (1,2,3,4,5);             //             Console.log (a.slice);  2            Console.log (A.slice (1,-1));  Console.log (A.slice (3,2));               []            //[1, 2, 3, 4, 5]

method is used to return a fragment or sub-array in an array, if only one parameter is written to return the parameter to the end of the array, and if the argument has a negative number, the tail count from the array (-3 means the array is the third, the average person does not do so, but not knowing the length of the array, want to discard the next n But the array length is good to know .... , good tangle usage), if start is greater than end returns an empty array, it is important to note that slice does not change the original array, but rather returns a new array.

Concat (Array)

It looks like a cut, but this is really not a concat. The method is used to stitch an array, a.concat (b) Returns a new array of A and B, and does not modify any of the original arrays, nor does it recursively concatenate arrays inside the array

var a=New Array (1,2,3,4,5);             var b=New Array (6,7,8,9);            Console.log (A.concat (b)); //  ////            [6, 7, 8, 9]            

Reverse ()

method is used to reverse the array, unlike before, it modifies the original array

var a=New Array (1,2,3,4,5);            A.reverse ();             // [5, 4, 3, 2, 1]

Similarly, when the array index is not sequential or starts at 0, the results need to be noted

var a=New  Array ();        a[2]=2;        a[3]=3;        a[7]=4;        a[8]=5;

A.reverse ();


The sort method is used to sort the array, and when no parameters are sorted in ascending alphabetical order, if the containing undefined is queued to the last side, the object element calls its ToString method, and if it wants to sort by its own definition, it can pass a sort method in, a typical policy mode, The same sort will change the original array.

var a=New Array (5,4,3,2,1);       A.sort ();       Console.log (a); //[1, 2, 3, 4, 5]


var a=New Array (7,8,9,10,11);       A.sort ();       Console.log (a); // [Ten, one, 7, 8, 9]

Since 7 is bigger than 10 in alphabetical order, we need to pass in a custom sort function

var a=New Array (7,8,9,10,11);           A.sort (function(v1,v2) {            return v1-v2;           });       Console.log (a); // [7, 8, 9, ten, one]

The principle is similar to the sort in C # (the design pattern in the. NET Framework-The Application policy mode is List sort), but can be passed directly into the method, the following is purely speculative

Sort internal using a quick sort, each time two element size is compared if there are no parameters, then directly determine the alphabet, if there are parameters, the two parameters being compared to the custom method and call (the two number being compared will be passed to the custom method V1, v2), if the return value is greater than 0 means v1> V2, if equal to 0, indicating V1=v2, if less than 0, means v1<v2, in fact, we passed the method is to tell sort how to compare two elements who are big who small, as for the sort of moving elements of the process people write well, guess the end.

At last

Understand these look at the array really is not ah, that is powerful and flexible, but in the traversal of elements, and get the location of the element is also a certain inconvenience, these have been resolved in ECMAScript, skilled use can make our JavaScript elegant and efficient.

6, ECMAScript5 New method

The importance of arrays in each programming language is self-evident, but in previous JavaScript arrays (JavaScript arrays in detail) have been very powerful, but the methods of operation are not perfect, and they have been properly supplemented in ECMAScript5.

Array.isarray (Element)

This is a static function of the array object that is used to determine whether an object is not an array

var New Array (123);         var New Date ();         // true        // false
. IndexOf (Element)/. LastIndexOf (Element)

As the name implies, these two methods are used to find the position of the specified element within the array, find the first one to return its index, and not find the return -1,indexof to search from beginning to finish, LastIndexOf reverse search.

var a=New Array (1,2,3,3,2,1);           Console.log (A.indexof (//1        //4
. ForEach (Element,index,array)

Iterate through the array, the parameter is a callback function, the callback function has three parameters: the current element, the element index, the entire array

var a=New Array (1,2,3,4,5,6);        A.foreach (function(e,i,array) {            array[i]=e+1;            });            // [2, 3, 4, 5, 6, 7]
. Every (function (Element,index,array))/. Some (function (Element,index,array))

These two functions are similar to the logical decision in discrete mathematics, and the callback function returns a Boolean value that returns True when each callback function of the "All" function returns true and terminates execution when the every is encountered, returning the False;some function as "exists" A callback function returns True when execution terminates and returns true, otherwise false is returned. Calling every on an empty array returns True,some returns FALSE.

var a=New Array (1,2,3,4,5,6);         /* 0:1         1:2        2:3        3:4         4:5         *        /Console.log (A.every (  function(e,i,arr) {            Console.log (i+ ': ' +e);             return e<5;            }));
var a=New Array (1,2,3,4,5,6);         /* 0:1         1:2        2:3        3:4         4:5         *        /Console.log (A.some (  function(e,i,arr) {            Console.log (i+ ': ' +e);             return e>4;            }));
. map (function (Element))

Similar to foreach, iterates through an array, returns a new array of callback functions, returns a new array with the same structure as the original array, and the original array unchanged

var a=New Array (1,2,3,4,5,6);        Console.log ( {            return e*e;             //         //[1, 2, 3, 4, 5, 6]
. filter (function (Element))

Returns a subset of the array in which the callback function is used to determine whether the logical return is returned, true to add the current element to the returned array, false to not add, the new array contains only values that return True, the index is missing, the original array remains unchanged

var a=New Array (1,2,3,4,5,6);        Console.log (a.filter (function(e) {            return e%2==0;             //         //[1, 2, 3, 4, 5, 6]
. reduce (function (V1,V2), value)/. Reduceright (function (V1,V2), value)

Iterate through the array, call the callback function, combine the elements of the array into a single value, reduce the index from the minimum value, reduceright the reverse, the method has two parameters

1. Callback function: The two values are combined into one, return the result

2.value, an initial value, optional

var a=New Array (1,2,3,4,5,6);        Console.log (a.reduce(function(v1,v2) {            return v1+v2;             //  +             Console.log (a.reduceright(function(v1,v2) {                return v1- v2;                }, //  -

JavaScript Learning--ITEM30 Array Advanced Full Mastery

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.