JavaScript array array method (Novice must read the article) _javascript skills

Source: Internet
Author: User
Tags array length javascript array

The array type is the most commonly used reference type in ECMAScript. The data in ECMAScript is quite different from the arrays in most other languages. Although the data in ECMAScript is an ordered list of data like an array in other languages, each item in the ECMAScript array can hold any type of data, whether numeric, string, or object. At the same time, the size of the array in ECMAScript can be dynamically adjusted, that is, you can automatically grow the data to accommodate the new data by adding it. Here's a summary of the common operation functions and usage of arrays in JavaScript.

• Create an array

The creation of an array consists primarily of two methods of constructors and arrays of literal quantities, as follows:

var arr = new Array (); 
var arr = []; 

For constructors, we can pass a numeric value to create an array that contains the given number of items , as follows:

var arr = new Array (3);  Array length is 3 

You can also pass the values stored in the array directly, as follows:

var arr = new Array ("Red", "green", "blue"); 

Either way, it is recommended to use the form of an array literal to create an array.

• Detecting arrays

For a single global execution environment, the instanceof operator can be used to detect whether an array, for example:

var arr = [1,2,3]; 
Console.log (arr instanceof Array);  True 

However, if a Web page contains multiple frames and contains multiple global execution environments, ES5 has added a Array.isarray () method to determine whether a value is an array, regardless of the global execution environment in which it was created, as follows:

if (Array.isarray (arr)) { 
    //perform certain actions 
} 

• Array String conversions

Each object has tolocalestring (), toString (), and valueof () methods. Calling the ToString () method of the array returns a comma-delimited string of strings of each value in the array, calling the ValueOf () method of the array to return an array, actually calling the ToString () method for each item in the array, as follows:

var arr = ["Red", "green", "Blue"]; 
Console.log (Arr.tostring ());  Red,green,blue 
Console.log (arr.valueof ());  Red,green,blue 
Console.log (arr);       Red,green,blue 

The toLocaleString () method that invokes the array, unlike ToString (), calls the toLocaleString () method of each item in the array, separating the return values of each tolocalestring () method by commas into a string. Using the Join () method, you can use a different separator to build this string, as follows:

var arr = ["Red", "green", "Blue"]; 
Console.log (Arr.join (","));  Red,green,blue 
Console.log (arr.join ("| |)");  red| | green| | Blue 

• Array additions and deletions

The push () method receives any number of arguments, adds them to the end of the array one by one, and returns the length of the modified array, for example:

var arr = [1,2,3]; 
Arr.push (4,5); 
Console.log (arr);  [1,2,3,4,5] 

Relative to push () is the Pop () method, which removes the last item from the end of the array and returns the removed item, for example:

var arr = [1,2,3]; 
Arr.pop ();  3 
Arr.pop ();  2 
Console.log (arr);  [1] 

The other two methods used are shift () and unshift (), which are similar to POPs () and push (), and the Shift () method is used to remove items from the beginning of the array and return the removed item, for example:

var arr = [1,2,3]; 
Arr.shift ();  1 
arr.shift ();  2 
Console.log (arr);  [3] 

The Unshift () method, instead of the shift (), can add any item to the front of the array and return the length of the new array, for example:

var arr = [1,2,3]; 
Arr.unshift (4);  Return length 4 
arr.unshift (5);  Return length 5 
console.log (arr);  [1,2,3,4,5] 

• Array flipping and sorting

The array provides a rollover method of reverse (), which reverses the order of data items, for example:

var arr = [1,2,3]; 
Arr.reverse (); 
Console.log (arr);  [3,2,1] 

Sort () can also be sorted by array, but its default sort is not size, but it is sorted by encoding according to the corresponding string. The sort () method can receive a comparison function for custom sorting, for example:

function Compare (value1,value2) {return 
  value1-value2; 
} 
var arr = [1,3,2,5,4]; 
Arr.sort (compare); 
Console.log (arr);  [1,2,3,4,5] 

• Array Connection

The Concat () method creates a copy of the current array, then adds the received parameter to the end of the replica, and finally returns the newly built array, which is unchanged, for example:

var arr = [1,2,3]; 
var arr2 = Arr.concat (4,[5,6]); 
Console.log (arr);  [1,2,3] 
console.log (ARR2);  [1,2,3,4,5,6] 

• Array segmentation

The slice () method receives one or two parameters, that is, to return the start and end positions of the items. If one argument is required, all items starting at the specified position and ending with the array are returned. If two parameters are received, all items between the start and end positions are returned but do not include the ending position, for example:

var arr = [1,2,3,4,5]; 
var arr2 = Arr.slice (1);  [2,3,4,5] 
var arr3 = Arr.slice (1,3);  [2,3] 

Note that the slice () method does not affect the original array.

Splice () method

Because the splice () method is very powerful, so take it out alone. To sum up, it can receive three parameters, the first parameter indicates where the item was added or deleted, the second parameter represents the number of items to delete, and the second parameter represents the new item added to the array (optional) and can be deleted by providing different parameters , insert, and replace features such as:

var arr = [1,2,3,4,5]; 
Arr.splice (2,0,11,22);  Insert two items from position 2 without deleting 
console.log (arr);  [1,2,11,22,3,4,5] 
 
arr.splice (2,2,33,44);  Deletes two items from position 2, inserts two items, returns the deleted item 
console.log (arr);  [1,2,33,44,4,5] 
 
arr.splice (1,1);  Deletes 1 items from position 1, returning the deleted item 
console.log (arr);  [1,33,44,4,5] 

• The location method of the array

ES5 provides two location methods: IndexOf () and LastIndexOf (). Both methods receive two parameters: the item to find and an optional index that represents the start position of the lookup. The IndexOf () method looks backwards from the beginning of the array, and LastIndexOf () looks forward from the end of the array, for example:

var arr = [1,2,3,4,5,4,3,2,1]; 
Console.log (Arr.indexof (4));  3 
Console.log (Arr.lastindexof (4));  5 
 
Console.log (Arr.indexof (4,4));  5 
Console.log (Arr.lastindexof (4,4));  3 

• Iterative Methods of arrays

ES5 defines 5 iterative methods, each of which receives two parameters: the function to run on each item and (optionally) the scope object that runs the function-the value that affects this. Functions passed in these methods can receive three parameters: the value of the array item, the index of the item in the array, and the group object itself.

Among them, the every () method and the Some () method are similar. For the Every () method, the Passed-in function must return true for each item, and this method returns True. For some (), the Passed-in function returns True if any of the entries in the array return true. Examples are as follows:

var arr = [1,2,3,4,5,4,3,2,1]; 
var everyresult = arr.every (function (item,index,array) {return 
  (item>2); 
}); 
Console.log (Everyresult);  False, not all greater than 2 
 
var someresult= arr.some (function (item,index,array) {return 
  (item>2); 
}); 
Console.log (Someresult);  True, an item greater than 2 can 

The filter () method determines whether an item is included in the returned array based on the given function, for example:

var arr = [1,2,3,4,5,4,3,2,1]; 
var filterresult = arr.filter (function (item,index,array) {return 
  (item>2); 
}); 
Console.log (Filterresult);  [3,4,5,4,3], returns an array of all values greater than 2 

The map () method runs the given function for each item in the array, and then returns an array of the results of each function run, for example:

var arr = [1,2,3,4,5,4,3,2,1]; 
var mapresult = Arr.map (function (item,index,array) {return 
  item*2; 
}); 
Console.log (Mapresult);  [2,4,6,8,10,8,6,4,2], each item of the original array multiplied by 2 returns 

The Last method is foreach (), which runs only the given function for each item in the array, with no return value, for example:

var arr = [1,2,3,4,5,4,3,2,1]; 
Arr.foreach (function (item,index,array) { 
  //Perform certain Operations 
}); 

• Method of narrowing the array

ES5 also provides two methods for narrowing the array: reduce () and reduceright (). Both methods iterate over all the items in the group, and then return a final value. Reduce () gradually traverses to the last item starting at the first entry, Reduceright () from the last entry to the end of the first item. Both functions receive four parameters: the previous value, the current value, the index of the item, and the array object. Any value returned by this function will be automatically passed to the next item as the first argument. For example, use the reduce () method to find the and of all items of an array:

var arr = [1,2,3,4,5]; 
var sum = arr.reduce (function (pre,cur,index,array) {return 
  pre+cur; 
}); 
Console.log (sum);  15 

The first time the callback function is executed, the pre is 1,cur 2. The second time, the pre is 3 (1+2), and the Cur is 3. This process accesses each item of the array and returns the result. The Reduceright () method is similar to reduce (), except in the opposite direction.

This note is mainly based on the JavaScript advanced programming and online resources summarized, if there is not perfect place also please point out.

The above is based on the JavaScript array method (Novice must read) is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.

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: info-contact@alibabacloud.com 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.