JavaScript Array Common operations

Source: Internet
Author: User
Tags javascript array

Objective

I believe that we are accustomed to jquery or underscore and other common array-related operations such as $.isarray,_.some,_.find and so on. Here is nothing more than the original JS array operation more packaging.

Here is a summary of common APIs for JavaScript array operations. I believe it is very helpful for us to solve the procedural problems.

1. Nature

An array in JavaScript is a special object that represents an index of an offset that is a property of that object, which is likely to be an integer. These numeric indexes are then internally converted to string types because the property name in the JavaScript object must be a string.

2. Operation

2.1 Determining array types

var array0 = [];    // literal quantity var New Array ();   // Constructors // Note: The Array.isarray method is not supported under IE6/7/8. alert (Array.isarray (array0)); // consider compatibility, and you can use instanceof Array); // or alert (Object.prototype.toString.call (array1) = = = ' [Object Array] ');

2.2 Arrays and strings

Very simple: convert arrays to strings, use join, convert strings to arrays, use split.

// Join-Converts an array into a string, using the Joinconsole.log ([' Hello ', ' World '].join (', '));    // Hello,world // split-converted by string to an array, using splitconsole.log (' Hello World '. Split ('));    //

2.3 Finding elements

It is believed that the string type indexof is commonly used, but it is seldom known that the indexof of an array can also be used to find elements.

//indexOf-Find elementConsole.log ([' ABC ', ' BCD ', ' CDE '].indexof (' BCD '));//1// varObjinarray =[{name:' King ', pass:' 123 '}, {name:' King1 ', pass:' 234 '}];console.log (Objinarray.indexof ({name:' King ', pass:' 123 '})); //-1varElementofarray = objinarray[0];console.log (Objinarray.indexof (Elementofarray)); //0

As can be seen from the above, for an array containing an array of objects, the IndexOf method is not a deep comparison to obtain the corresponding search results, only the comparison of the corresponding elements of the reference.

2.4 Array Connections

With concat, it is important to note that a new array is generated after using Concat.

var array1 = [1, 2, 3]; var array2 = [4, 5, 6]; var // after the array connection is implemented, a new array Console.log (ARRAY3) is created;

2.5 Class list Operations

For adding elements, you can use push and unshift, respectively, to remove elements using pop and shift.

//Push/pop/shift/unshiftvarArray = [2, 3, 4, 5];//add to Tail of arrayArray.push (6); Console.log (array); //[2, 3, 4, 5, 6]//add to Array headerArray.unshift (1); Console.log (array); //[1, 2, 3, 4, 5, 6]//remove the last elementvarElementofpop =Array.pop (); Console.log (Elementofpop); //6Console.log (array);//[1, 2, 3, 4, 5]//removing the first elementvarElementofshift =Array.shift (); Console.log (Elementofshift); //1Console.log (array);//[2, 3, 4, 5]

2.6 Splice Method

Main two uses:

1> adding and removing elements from an array's middle position

2> from the original array, get a new array

Of course, two uses are synthetic, some focus on the use of one, some focus on the use of two.

Adding and removing elements from the middle of an array, the Splice method adds elements to the arrays, providing the following parameters

1> Start index (where you want to start adding elements)

2> the number of elements that need to be deleted or the number of elements extracted (this parameter is set to 0 when the element is added)

3> the element you want to add into the array

var nums = [1, 2, 3, 7, 8, 9];nums.splice (3, 0, 4, 5, 6); Console.log (nums);   //  //  immediately follow the delete operation or extract the new array var newnums = Nums.splice (3, 4); Console.log (nums)  ; // [1, 2, 3, 8, 9]Console.log (newnums);   //

2.7 Sort

This article mainly introduces reverse and sort two methods. Array inversion using the Reverse,sort method can be used not only for simple sorting, but also for complex sorting.

// invert an array var array = [1, 2, 3, 4, 5//  [5, 4, 3, 2, 1]

Let's sort the array of string elements first

var arrayofnames = ["David", "Mike", "Cynthia", "Clayton", "Bryan", "Raymond"];arrayofnames.sort (); Console.log (arrayofnames);   //

We sort the array of numeric elements

// if the array element is a numeric type, the sort () method does not make people happy. var nums = [3, 1, 2, 4,];nums.sort (); Console.log (nums);   //

The sort method sorts the elements in a dictionary order, so it assumes that the elements are string types, so even if the element is a numeric type, it is considered a string type. At this point, a size comparison function can be passed in when the method is called, and the sort () method will compare the size of the two elements in the array according to the function, thus determining the order of the entire array.

var function (NUM1, num2) {    return num1 > num2;}; Nums.sort (Compare); Console.log (nums);   //
 var  objinarray = [{name:  ' King '  ' 123 ' , index:  2 ' king1 '  ' 234 ' , index:  1 //  var  compare =  (O1, O2) { return  o1.index > O2.index;}; Objinarray.sort (Compare); Console.log (objinarray[ 0].index < Objinarray[1].index); //  

2.8 Iterator Method

Mainly includes foreach and every, some and map, filter

foreach believes everyone will, mainly introduce the other four ways.

The Every method takes a function that returns a Boolean type that uses the function for each element in the array. If the function returns true for all elements, the method returns True.

var nums = [2, 4, 6, 8]; // iterator method that does not generate a new array var function (num) {    return num% 2 = = = 0;}; // returns True if all are even // true

The Some method also accepts a function that returns a Boolean type, which returns true whenever an element causes the function to return true.

var function (num) {    return num% 2 = = = 0;}; var nums1 = [1, 2, 3, 4//  true

JavaScript Array Common operations

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.