Common JavaScript Array Operations

Source: Internet
Author: User
This article mainly introduces common JavaScript Array Operation Skills, and summarizes various common operation skills for Array search, connection, sorting, and iteration in the form of examples, which is of great practical value, for more information, see the 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

Var array0 = []; // var array1 = new Array (); // constructor // Note: Array 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.

// Join-converts an array to a string using joinconsole. log (['hello', 'World']. join (','); // Hello, World // split-converts a string to an array using the splitconsole. 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.

// IndexOf-search for the console element. log (['abc', 'bcd', 'cde']. indexOf ('bcd'); // 1 // var objInArray = [{name: 'King', pass: '000000'}, {name: 'king1', pass: '20140901'}]; console. log (objInArray. indexOf ({name: 'King', pass: '000000'}); //-1var 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.

Var array1 = [1, 2, 3]; var array2 = [4, 5, 6]; var array3 = array1.concat (array2); // After the array is connected, A new array console is created. 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.

// Push/pop/shift/unshiftvar array = [2, 3, 4, 5]; // Add it to the array End. push (6); console. log (array); // [2, 3, 4, 5, 6] // Add it 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); // 6console. log (array); // [1, 2, 3, 4, 5] // remove the first element var elementOfShift = array. shift (); console. log (elementOfShift); // 1console. 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

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 or extract 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 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.

// Reverse the array var array = [1, 2, 3, 4, 5]; array. reverse (); console. log (array); // [5, 4, 3, 2, 1] We first sort the array of string elements. 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.

// If the array element is numeric, 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.

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: '2013', index: 2 }, {name: 'king1', pass: '20170101', 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.

Var nums = [2, 4, 6, 8]; // The iterator method var isEven = function (num) that does not generate a new array) {return num % 2 === 0 ;}; // returns trueconsole only if all values are even. log (nums. every (isEven); // the truesome method also accepts a function with a Boolean return value. If an element returns true for the function, 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:

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.

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.