JavaScript array Common operation skills Summary _javascript Tips

Source: Internet
Author: User
Tags array to string javascript array

This example summarizes the common how-to techniques for javascript arrays. Share to everyone for your reference. Specifically as follows:

Objective

I believe that we are used to jquery or underscore and other such libraries commonly used in the array-related operations, such as $.isarray,_.some,_.find and so on. Here is nothing more than the original JS array operation of some more packaging.
Here is a summary of the most common APIs for JavaScript array operations. I believe it is very helpful for us to solve the problem of procedure.

First, the Nature
an array in JavaScript is a special object, and the index that represents the offset is an attribute of the object, which may be an integer. However, these numeric indices are internally converted to string types because the property names in the JavaScript object must be strings.

Second, the operation

1 Judging array types

Copy Code code as follows:
var array0 = []; Literal amount
var array1 = new Array (); Construction device
Note: The Array.isarray method is not supported under IE6/7/8
Alert (Array.isarray (array0));
Consider compatibility, which you can use
Alert (array1 instanceof Array);
Or
Alert (Object.prototype.toString.call (array1) = = ' [Object Array] ');

2 Arrays and strings

Very simple: Convert from array to string, use Join, convert from string to array, use split.

Copy Code code as follows:
Join-converts from an array to a string, using join
Console.log (' Hello ', ' World '].join (', ')); Hello,world
Split-Converts an array by string, using split
Console.log (' Hello World '. Split (")); ["Hello", "World"]

3 Finding elements

I believe we all use String type indexof, but it's very rare to know that the indexof of an array can also be used to find elements.

Copy Code code as follows:
IndexOf-Find elements
Console.log ([' ABC ', ' BCD ', ' CDE '].indexof (' BCD ')]; 1

//
var Objinarray = [
{
Name: ' King ',
Pass: ' 123 '
},
{
Name: ' King1 ',
Pass: ' 234 '
}
];

Console.log (Objinarray.indexof ({
Name: ' King ',
Pass: ' 123 '
})); -1

var elementofarray = objinarray[0];
Console.log (Objinarray.indexof (Elementofarray)); 0

As can be seen from the above, for the array containing the object of this array, the IndexOf method is not a deep comparison to get the corresponding search results, just compare the reference of the corresponding elements.

4 Array Connection

With Concat, note that a new array is generated after using Concat.

Copy Code code as follows:
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
var array3 = Array1.concat (array2); After an array connection is implemented, a new array is created
Console.log (ARRAY3);

5 Class list Operations

For adding elements, you can use push and unshift separately, and you can remove elements by using both pop and shift.

Copy Code code as follows:
Push/pop/shift/unshift
var array = [2, 3, 4, 5];

Add to Tail of array
Array.push (6);
Console.log (array); [2, 3, 4, 5, 6]

Add to Array header
Array.unshift (1);
Console.log (array); [1, 2, 3, 4, 5, 6]

Remove the last element
var elementofpop = Array.pop ();
Console.log (Elementofpop); 6
Console.log (array); [1, 2, 3, 4, 5]

Remove the first element
var elementofshift = Array.shift ();
Console.log (Elementofshift); 1
Console.log (array); [2, 3, 4, 5]

6 Splice method

Main two uses:
① Add and remove elements from the middle of an array
② from the original array, get a new array

Of course, two uses are in the synthesis, some scenes focus on the use of one, some focus on the use of two.

Adds and deletes elements from the middle of an array, and the splice method adds elements to the arrays, providing the following parameters
① starting index (that is, where you want to start adding elements)
② 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)
③ elements you want to add to the array

Copy Code code as follows:
var nums = [1, 2, 3, 7, 8, 9];
Nums.splice (3, 0, 4, 5, 6);
Console.log (Nums); [1, 2, 3, 4, 5, 6, 7, 8, 9]
Then do the delete operation or fetch the new array
var newnums = Nums.splice (3, 4);
Console.log (Nums); [1, 2, 3, 8, 9]
Console.log (newnums); [4, 5, 6, 7]

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.

Copy Code code as follows:
Reverse Array
var array = [1, 2, 3, 4, 5];
Array.reverse ();
Console.log (array); [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); ["Bryan", "Clayton", "Cynthia", "David", "Mike", "Raymond"]

We sort the array of numeric elements
Copy Code code as follows:
If the array element is a numeric type, the sort result of the sort () method is not satisfactory.
var nums = [3, 1, 2, 100, 4, 200];
Nums.sort ();
Console.log (Nums); [1, 100, 2, 200, 3, 4]

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, you can pass in a size comparison function when you call the method, and the sort () method will compare the size of the two elements in the array based on that function to determine the order of the entire array.
Copy Code code as follows:
var compare = function (NUM1, num2) {
return NUM1 > num2;
};
Nums.sort (Compare);
Console.log (Nums); [1, 2, 3, 4, 100, 200]

var Objinarray = [
{
Name: ' King ',
Pass: ' 123 ',
Index:2
},
{
Name: ' King1 ',
Pass: ' 234 ',
Index:1
}
];
An object element in an array, ascending according to index
var compare = function (O1, O2) {
return o1.index > O2.index;
};
Objinarray.sort (Compare);
Console.log (Objinarray[0].index < Objinarray[1].index); True

8 Iterator method

Mainly includes foreach and every, some and map, filter
foreach believes that all of us will introduce the other four methods.
The Every method accepts a function that returns a Boolean type, which is used by each element in the array. If the function returns true for all elements, the method returns True.

Copy Code code as follows:
var nums = [2, 4, 6, 8];
An iterator method that does not generate a new array
var isEven = function (num) {
return num% 2 = 0;
};
Returns true if both are even numbers
Console.log (Nums.every (IsEven)); True

The Some method also accepts a function that returns a Boolean type, and returns True whenever an element makes the function return true.
var isEven = function (num) {
return num% 2 = 0;
};
var nums1 = [1, 2, 3, 4];
Console.log (Nums1.some (IsEven)); True

Both the map and filter methods can produce a new array, and the new array returned by the map is the result of applying a function to the original element. Such as:

Copy Code code as follows:
var up = function (grade) {
Return grade + + 5;
}
var grades = [72, 65, 81, 92, 85];
var newgrades = grades.ma

The filter method is similar to the every method, passing in a function that returns a Boolean type. Unlike the Every () method, when all elements in an array apply the function and the result is true, the method does not return true, but instead returns a new array containing elements that have the result true when the function is applied.
Copy Code code as follows:
var isEven = function (num) {
return num% 2 = 0;
};
var isodd = function (num) {
Return num% 2!== 0;
};
var nums = [];
for (var i = 0; i < i++) {
Nums[i] = i + 1;
}
var evens = Nums.filter (IsEven);
Console.log (evens); [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
var odds = Nums.filter (isodd);
Console.log (odds); [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Third, summary

There are also some methods that are not supported by low-level browsers and need to be implemented with other methods.

These are common methods that may not be easy for everyone to think of. You may wish to pay more attention to it.

I hope this article will help you with your JavaScript programming.

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.