Summary of JavaScript Array Methods

Source: Internet
Author: User
Tags javascript array
Arrays in JavaScript are very special. Unlike arrays and lists in C or Java, arrays in JS can be used as a stack or queue, four major operations: pop, push, shift, and unshift.

Arrays in JavaScript are very special. Unlike arrays and lists in C or Java, arrays in JS can be used as a stack or queue, four major operations: pop, push, shift, and unshift.

For an array method, there are two most important issues,What is the returned value? Will it affect the original array?A typical example is the splice and slice methods. For functions that return the original array, we can directly call the chain call of the array, which is cool (array. filter (). sort (). reverse ()).

With these two questions, I would like to summarize the Array method of Array.

Array

Array. length is the length of the Array. Each newly created Array object has a length object. You can use Array. prototype is used to modify the prototype, but the basic use and operation of arrays are not the focus of today. Let's look at the array method.

Generally, the array method will end with a thisArg parameter, which specifies the internal point of this. If there is a return function in the parameter, this return function generally accepts three parameters: value, index, and array, representing the currently passed value, respectively, the index of the currently passed in value and the current processed array.

Directory Index:

Concat

This method can be used for Array concatenation. The parameter is one or more arrays, and the returned result is an array.

The concat method creates a new array, and then calls its object (the object that this points to, that is, the original array) elements and elements in all parameters of the array type and parameters of the non-array type are placed in the new array in order, and the array is returned. The concat method does not modify the original array and parameter array, and has the same effect on non-array objects.

  1. Returns the new spliced array;

  2. Do not modify the original array and parameter array;

  3. The parameter can be a non-array.

var a1 = [1, 2, 3],  a2 = [4, 5, 6],  a3 = [7, 8, 9];var newarr = a1.concat(a2, a3);newarr //[1, 2, 3, 4, 5, 6, 7, 8, 9]a1 //[1, 2, 3]newarr = a1.concat(4, a3);//[1, 2, 3, 4, 7, 8, 9]newarr = a1.concat('hello');//[1, 2, 3, "hello"]
Every

The every () method tests whether all elements of the array have passed the test of the specified function.

Arr. every (callback) executes the callback method for each element until the callback returns false. Sometimes the every method is compared with the forEach method, because forEach cannot be stopped, while the every method can be stopped halfway when returning flase.

  1. If all tests are passed, the function returns true, exits midway, and false;

  2. Does not affect the original array.

function isBigEnough(element, index, array) {  console.log(index);  return (element >= 10);}var passed = [12, 5, 8, 130, 44].every(isBigEnough);// 0// 1// passed is falsepassed = [12, 54, 18, 130, 44].every(isBigEnough);// 0 1 2 3 4// passed is true
Filter

The filter () method tests all elements using the specified function and creates a new array containing all elements that pass the test.

In fact, this method is a filtering method. The previous every method only checks whether it is not filtered. The filter filters out some non-conforming items and returns a new array.

  1. Returns a new array that meets the filtering conditions;

  2. The original array is not changed.

function isBigEnough(element, index, array) {  return (element >= 10);}var a1 = [19, 22, 6, 2, 44];var a2 = a1.filter(isBigEnough);a1 //[19, 22, 6, 2, 44]a2 //[19, 22, 44]
ForEach

The forEach () method executes the provided function (callback function) for each element of the array once ).

  1. The function has no return value, that is, underfined;

  2. Does not affect the original array.

Function logArrayElements (element, index, array) {console. log ("a [" + index + "] =" + element);} // note that index 2 is skipped, because there is no var result = [2, 5, 9] in this position of the array. forEach (logArrayElements); // a [0] = 2 // a [1] = 5 // a [2] = 9 result // underfined
IndexOf

The indexOf () method returns the first index value that can be found in the array for the given element. Otherwise,-1 is returned.

  1. The returned value is the index value or-1 of the element;

  2. Does not affect the original array.

var array = [1, 2, 5];array.indexOf(5); // 2array.indexOf(7); // -1
Join

The join () method concatenates all elements in the array into a string.

In fact, for join, the first operation is the string split operation. These two operations are often used together to process strings.

  1. Returns the concatenated string;

  2. Does not affect the original array.

var a1 = [1, 2, 3];var a2 = a1.join();a1 //[1, 2, 3]a2 //"1,2,3"a2 = a1.join("");//"123"a2 = a1.join("-");//"1-2-3"
LastIndexOf

The lastIndexOf () method returns the last index of the specified Element (that is, a valid JavaScript value or variable) in the array. If it does not exist,-1 is returned. Search forward from the back of the array, starting from fromIndex.

In fact, this is the version of indexOf.

  1. Returns the index of the first element;

  2. Does not affect the original array.

var array = [2, 5, 9, 2];var index = array.lastIndexOf(2);// index is 3index = array.lastIndexOf(7);// index is -1index = array.lastIndexOf(2, 3);// index is 3index = array.lastIndexOf(2, 2);
Map

The map () method returns a new array consisting of the returned values after each element in the original array calls a specified method.

Map reduce functions have always been the top two in array processing, bringing great convenience.

  1. Returns a new array processed by the return function;

  2. Does not affect the original array.

var a1 = [1, 4, 9];var a2 = a1.map(Math.sqrt);a1 //[1, 4, 9]a2 //[1, 2, 3]
Reduce

The reduce () method receives a function as an accumulator. Each value in the array (from left to right) is merged into a value.

Reduce is a process of merging, from left to right until all elements are merged and the final result is returned. It accepts two parameters. The first parameter is a return function, and the second parameter is an initial value, indicating the previous value when processing the first element. The return function accepts four parameters: accumulator (result of last processing), currentValue (value of the current element), index (index of the current element ), array (the array that calls reduce ).

  1. Return the final merging result, that is, return the output of the function, which can be any string, object, array, and other results;

  2. Does not affect the original array.

var getAdd = (pre, cur) => pre + cur;var a1 = [1, 2, 3];var a2 = a1.reduce(getAdd, 0);a1 //[1, 2, 3]a2 //6
ReduceRight

The reduceRight () method accepts a function as an accumulator, reducing each value (from right to left, that is, from the end to the header) to a value. (Opposite to reduce () execution)

var toStr = (pre, cur) => '' + pre + cur;var a1 = [1, 2, 3];var a2 = a1.reduce(toStr, '');a2 //"123"a2 = a1.reduceRight(toStr, '');a2 //"321"
Push

Add one or more elements to the end of the array in the push () method, and return the new length (length attribute value) of the array ).

If the array is used as the stack, the push pop operation is the stack entry and exit, and many people usually ignore the returned values after function execution.

  1. Returns the length of the array after the push operation is executed;

  2. Definitely changed.

var a1 = [1, 2, 3];var a2 = a1.push(4);a1 //[1, 2, 3, 4]a2 //4
Pop

The pop () method deletes the last element in an array and returns this element.

  1. Returns the deleted element;

  2. Definitely changed.

var a1 = [1, 2, 3];var a2 = a1.pop();a1 //[1, 2]a2 //3
Unshift

The unshift () method adds one or more elements at the beginning of the array and returns the new length Value of the array.

  1. Returns the length value;

  2. Definitely changed.

var a1 = [1, 2, 3];var a2 = a1.unshift(4);a1 //[4, 1, 2, 3]a2 //4
Shift

The shift () method deletes the first element of the array and returns this element. This method changes the length of the array.

The shift and push methods can form a queue operation.

  1. Returns the deleted element;

  2. Definitely changed.

Reverse

The reverse () method reverses the positions of elements in the array. The first element becomes the last one, and the last one becomes the first one.

  1. The Return Value of the function is the modified original array;

  2. The original array is modified.

var a1 = [1, 2, 3];var a2 = a1.reverse();a1 //[3, 2, 1]a1 === a2; //true
Slice

The slice () method replicates a portion of the shallow copy array to a new array and returns the new array.

Slice parameters include the initial position and end position of the copy (left closed and right open), which are different from splice. Because the original array is not changed, this array can be used for pre-Copy. For example, it is often seen that arr. slice (0) is used to copy the array.

  1. Returns the new array after the shortest copy;

  2. The original array is not changed.

var a1 = [1, 2, 3, 4, 5];var a2 = a1.slice(1, 3);a1 //[1, 2, 3, 4, 5]a2 //[2, 3]
Splice

The splice () method replaces the old element with the new element to modify the content of the array.

If it is separated by its name, the content of the original array will be modified, and a new array will be returned, with many parameters. The first parameter indicates the initial position, and the second parameter indicates the split length, the third parameter and later indicates that a new element is added to the split.

  1. Returns an array composed of split elements;

  2. The array is modified, and the original array is subtracted from the split array.

var a1 = [1, 2, 3, 4];var a2 = a1.splice(1, 2);a1 //[1, 4]a2 //[2, 3]a1 = [1, 2, 3, 4];a2 = a1.splice(1, 2, 5, 6);a1 //[1, 5, 6, 4]
Some

The some () method tests whether some elements in the array have passed the test of the specified function.

Sort

The sort () method sorts the elements of the array in the same place and returns the array. The sort sorting may be unstable. By default, it is sorted by the Unicode code point of the string.

The sort function is usually used for sorting. If there is no sorting function, it is sorted by the unicode position, and the number is converted into a string, so '123' is placed behind '11.

We will use sort to make some interesting sorting, such as sorting Chinese characters by pinyin.

  1. Returns the original sorted array;

  2. The array is modified.

var big = function(a, b){  return a - b;}var a1 = [2, 4, 77, 1];var a2 = a1.sort(big);a1 //[1, 2, 4, 77]a1 === a2; //true

LocaleCompare can be used to sort Chinese characters. When both Chinese characters and letters appear, a bug occurs:

Var sort_py = function (a, B) {return. localeCompare (B);} var a1 = ["Beijing", "Shanghai", "Nanjing", "Hefei"]; a1.sort (sort_py); // ["Beijing ", "Hefei", "Nanjing", "Shanghai"]
ToString

ToString () returns a string that represents the specified array and its elements.

Obviously, this method is compared with the join method.

  1. Returns the concatenated string;

  2. The original array is not changed.

var a1 = [1, 2, 3];var a2 = a1.toString();a2 //"1,2,3"
Array method added in ES6

All of the above methods are ES5. Let's take a look at which new methods are added to ES6.

CopyWithin

The copyWithin () method copies partial elements of an array to different positions of the same array without changing the array size. This array is returned.

Three parameters are accepted: target, start, and end.

  1. Returns the modified original array;

  2. The array is modified, and it is a shortest copy;

  3. The parameter can be negative. If the value is negative, it is reversed. If the end is null, it indicates the array length.

var a1 = [1, 2, 3, 4, 5];var a2 = a1.copyWithin(0, 2, 4);a1 //[3, 4, 3, 4, 5]a2 //[3, 4, 3, 4, 5]a1 === a2; //true
Find

If an element in the array meets the test conditions, the find () method returns the first element that meets the conditions. If no element meets the conditions, undefined is returned. MDN array. find.

  1. The element found. If not found, underfined is returned.

  2. Does not affect the original array.

function isBigEnough(element, index, array) {  return (element >= 10);}var a1 = [8, 18, 14];var num = a1.find(isBigEnough); //18
FindIndex

The findIndex () method is used to search for the index of a specified Element in the array. If the specified element cannot be found,-1 is returned.

This method can be referred to the find method, but the returned value is the index of the element rather than the element itself.

Fill

The fill () method can be used to replace or fill the values of all elements in the specified range in an array with a fixed value.

The fill method accepts three parameters. The value of the first parameter indicates that the value is to be filled in. the start and end parameters are optional and left-closed and right-open.

  1. The Return Value of the function is the modified original array;

  2. Can affect the array.

var a1 = [1, 2, 3, 4, 5];var a2 = a1.fill(6, 1, 4);a1 //[1, 6, 6, 6, 5]a2 //[1, 6, 6, 6, 5]a1 === a2; //true
Keys

The array keys () method returns an array index iterator.

This method returns an iterator for the array index, which has a special purpose in es6.

  1. The function returns an iterator object;

  2. The original array is not changed.

var arr = ["a", "b", "c"];var iterator = arr.keys();console.log(iterator.next()); // { value: 0, done: false }console.log(iterator.next()); // { value: 1, done: false }console.log(iterator.next()); // { value: 2, done: false }console.log(iterator.next()); // { value: undefined, done: true }
Entries

The entries () method returns an Array Iterator object that contains the key-value pairs of each index in the Array.

var arr = ["a", "b", "c"];var eArr = arr.entries();console.log(eArr.next().value); // [0, "a"]console.log(eArr.next().value); // [1, "b"]console.log(eArr.next().value); // [2, "c"]
Includes

The pair des () method is used to determine whether the current array contains a specified value. If yes, true is returned. Otherwise, false is returned.

This function accepts two parameters. The second parameter indicates that the start position is 0. The biggest difference between this method and the indexOf method is that the return value is an index, and the return value is a Boolean value. The indexOf method uses = to determine the NaN condition, des can be judged.

  1. Returns true or false;

  2. The original array is not changed.

var a1 = [1, NaN];a1.indexOf(NaN);//-1a1.includes(NaN);//true

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.