Common JavaScript Array Operation tips, javascript Array

Source: Internet
Author: User
Tags javascript array

Common JavaScript Array Operation tips, javascript Array

This example summarizes common operations on JavaScript arrays. Share it with you for your reference. The details are as follows:

Preface

I believe everyone is familiar with array-related operations commonly used in these class libraries such as jquery or underscore, such as $. isArray, _. some, _. find, and so on. Here is nothing more than some packaging for native js Array Operations.
Here we will summarize common APIs for JavaScript Array Operations. I believe it will be helpful for you to solve program problems.

I. Nature
Arrays in JavaScript are special objects used to indicate that the index of the Offset is the property of the object, and the index may be an integer. However, these numeric indexes are converted to the string type internally, because the property name in the JavaScript Object must be a string.

Ii. Operations

1. Determine the array type
Copy codeCode: var array0 = []; // literal
Var array1 = new Array (); // Constructor
// Note: the Array. isArray method is not supported in IE6/7/8.
Alert (Array. isArray (array0 ));
// Considering compatibility, you can use
Alert (array1 instanceof Array );
// Or
Alert (Object. prototype. toString. call (array1) === '[object Array]');

2 arrays and strings

Very simple: converts an array to a string, uses join, converts a string to an array, and uses split.
Copy codeThe Code is as follows: // join-converts an array to a string and uses join
Console. log (['hello', 'World']. join (','); // Hello, World
// Split-convert string to array and use split
Console. log ('Hello world'. split (''); // [" Hello "," World "]

3. Search for elements

I believe that indexOf, a string type, is commonly used, but it is seldom known that the indexOf array can also be used to search for elements.
Copy codeThe Code is as follows: // indexOf-search Element
Console. log (['abc', 'bcd', 'cde']. indexOf ('bcd'); // 1

//
Var objInArray = [
{
Name: 'King ',
Pass: '20140901'
},
{
Name: 'king1 ',
Pass: '20140901'
}
];

Console. log (objInArray. indexOf ({
Name: 'King ',
Pass: '20140901'
}); //-1

Var elementOfArray = objInArray [0];
Console. log (objInArray. indexOf (elementOfArray); // 0

As can be seen from the above, for an array containing objects, the indexOf method is not to obtain the corresponding search result through in-depth comparison, but to compare the reference of the corresponding element.

4. array connection

Note that a new array is generated after concat is used.
Copy codeThe Code is as follows: var array1 = [1, 2, 3];
Var array2 = [4, 5, 6];
Var array3 = array1.concat (array2); // After array connection is implemented, a new array is created.
Console. log (array3 );
Category 5 List operations

It is used to add elements. push and unshift can be used respectively, and pop and shift can be used to remove elements respectively.
Copy codeThe Code is as follows: // push/pop/shift/unshift
Var array = [2, 3, 4, 5];

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

// Add to the 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

Two main purposes:
① Add and delete elements from the middle of the array
② Obtain a new array from the original array

Of course, the two purposes are one-to-one synthesis. Some scenarios focus on one-to-one, while others focus on second-to-second.

Add and delete elements from the middle of the array. The splice method adds elements to the array. The following parameters must be provided:
① Start index (where you want to start adding elements)
② Number of elements to be deleted or the number of extracted elements (this parameter is set to 0 when an element is added)
③ Elements to be added to the array
Copy codeThe Code is 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]
// Delete the object or extract a 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 section describes the reverse and sort methods. Array inversion uses reverse. The sort method can be used not only for simple sorting, but also for complex sorting.
Copy codeThe Code is as follows: // reverse the Array
Var array = [1, 2, 3, 4, 5];
Array. reverse ();
Console. log (array); // [5, 4, 3, 2, 1]
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"]
Sort the array of numeric elements.
Copy codeThe Code is as follows: // If the array element is of the numeric type, the sorting result of the sort () method will not be satisfactory.
Var nums = [3, 1, 2,100, 4,200];
Nums. sort ();
Console. log (nums); // [1,100, 2,200, 3, 4]
The sort method sorts elements in alphabetical order. Therefore, it assumes that all elements are strings. Therefore, even if the elements are digits, they are considered strings. In this case, you can pass in a size comparison function when calling a method. During sorting, the sort () method compares the size of the two elements in the Array Based on the function to determine the order of the entire array.
Copy codeThe Code is 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: '20140901 ',
Index: 2
},
{
Name: 'king1 ',
Pass: '20140901 ',
Index: 1
}
];
// Sort the object elements in the array in ascending order based on the 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

It mainly includes forEach, every, some, map, and filter.
ForEach I believe everyone will introduce the other four methods.
The every method accepts a function whose return value is Boolean and uses this function for each element in the array. If the function returns true for all elements, the method returns true.
Copy codeThe Code is as follows: var nums = [2, 4, 6, 8];
// The iterator method that does not generate a new array
Var isEven = function (num ){
Return num % 2 = 0;
};
// Returns true only if all values are even.
Console. log (nums. every (isEven); // true

Some methods also accept a function whose return value is boolean. If an element causes the function to return true, the method returns true.
Var isEven = function (num ){
Return num % 2 = 0;
};
Var nums1 = [1, 2, 3, 4];
Console. log (nums1.some (isEven); // true

Both map and filter methods can generate a new array. The new array returned by map is the result of applying a function to the original element. For example:
Copy codeThe Code is 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. A function with a Boolean return value is input. Different from the every () method, when this function is applied to all elements in the array and the result is true, this method does not return true, but returns a new array, this array contains the elements whose result is true after the function is applied.
Copy codeThe Code is 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 <20; 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]

Iii. Summary

Some of the above methods are not supported by low-level browsers, and other methods must be used for compatibility.

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

I hope this article will help you design javascript programs.

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.