Some common methods of arrays in JavaScript

Source: Internet
Author: User
Tags array length

In JavaScript, the Array type should be the most common type, except for object. Each of its items can hold any type of data, that is, you can use the first position of the array to hold the string, the second position to hold the value, the third position to hold an object, and so on.

Some common methods of arrays in JavaScript

1, there are some ways to change the values of the objects that call them when they are called, such as push, pop, unshift, shift, sort, splice, reverse, and so on, and the functions of each method are explained below.

The push () method is to add one or more elements at the end of the array and put back the length of the new array.

 let arr=["Red", "green", "Blue"];let len=arr.push ("yellow"); Console.log (arr);//["Red", "green "," Blue "," yellow "]
Console.log (len);//4

  

The Pop () method deletes an element at the end of the array and returns the element.

 let arr=["Red", "green", "blue", "yellow"]; Let elem=Arr.pop (); Console.log (arr);//["Red", "green", "Blue"]console.log (elem);//"Yellow"

  

The Unshift () method is to add one or more elements at the beginning of the array and return the length of the new array

 let arr=["Red", "green", "Blue"; Let Len=arr.unshift ("yellow", "white"); Console.log (arr);//["Yellow", "white", "red", "green", "Blue"]console.log (len);//5

The shift () method is to delete the first element of the array and return the element

Let arr=["Red", "green", "Blue"];let elem=arr.shift (); Console.log (arr);//["Green", "Blue"] Console.log ( Elem);//"Red"

The sort () method sorts the elements in an array and returns the current arrays. The default sort order is based on the Unicode code point of the string

Let arr=["Red", "green", "blue"];let result=arr.sort (); Console.log (arr);//["Blue", "green", "blue"] Console.log (result); //["Blue", "green", "blue"

Let arrnum=[10,5,20,7,1];
Let Resultnum=arrnum.sort ();//the number is converted to a string when compared here
Console.log (arrnum);//[1, 10, 20, 5, 7]
Console.log (resultnum);//[1, 10, 20, 5, 7]

The sort () method has a parameter that is a function that can be sorted by the specified rule. If a comparison function is indicated, the array is sorted by the return value of the comparison function. such as Comparefunction (A, b), where A and B are two elements to be compared, the return value is as follows.

1, if a < B, the return value is less than 0, that is, a is in front of b

2, if a = B, the return value equals 0.

3, if a > B, the return value is greater than 0. That a is at the back of B.

If the array of comparisons is full of numbers, you can compare the functions to a A-B, as the following arrays will be sorted in ascending order

Let arrnum=[10,5,20,7,1];  let result=arrnum.sort (comparenumbers); function Comparenumbers (A, a    ) {return A-b;} Console.log (arrnum);//[1, 5, 7, 7, 20]console.log (result);//[1, 5,, ten)

The splice () method changes the value of an array by removing existing elements and adding new elements. The return value is an array of deleted elements. If only one element is deleted, an array containing only that element is returned. If no element is deleted, an empty array is returned. The method has three parameters, and the 1th parameter represents the location of the added/deleted element. The 2nd parameter indicates the number of elements to delete, and if 0, the element is not deleted. The 3rd parameter represents the content of the element to be added. The 2nd and 3rd parameters are optional if omitted to delete the element from the 1th parameter to the end of the array.

 Letarr=[1,2,3,4,5,6,7]; LetResult=arr.splice (3); Console.log (arr);//[1, 2, 3]Console.log (result);//[4, 5, 6, 7]
LetResult=arr.splice (3,1); Console.log (arr);//[1, 2, 3, 5, 6, 7]Console.log (result);//[4]
LetResult=arr.splice (3,1,8,9); Console.log (arr);//[1, 2, 3, 8, 9, 5, 6, 7]Console.log (result);//[4]

Let Result=arr.splice ( -3,1,8,9);
Console.log (arr);//[1, 2, 3, 4, 8, 9, 6, 7]
Console.log (result);//[5]

The reverse () method reverses the element position of the array, that is, the original first element becomes the last, and the last element becomes the first

Let arr=["Red", "green", "blue"];let result=arr.reverse (); Console.log (arr); // ["Blue", "green", "red"]console.log (result); // ["Blue", "green", "red"]

2, the following methods will never change the value of the object that invokes them, but will return only a new array or a different expectation. such as: Concat, join, Slice, indexOf, lastIndexOf, toString

The Concat () method returns a new array composed of the current array and several other arrays or several non-array values. This method does not change the existing array but returns a new array 

 let arr=["Red", "green", "Blue"; Let conarr=["yellow", "white"];  let result=arr.concat (Conarr); Console.log (arr); // ["Red", "green", "blue"]console.log (result); // ["Red", "green", "blue", "yellow", "white"]

The join () method joins the array elements into a string

 let arr=["Red", "green", "Blue";  let Result=arr.join (); // You can specify a separator defaults think,console.log (arr); // ["Red", "green", "blue"]console.log (result); // Red,green,blue  Let Resultsep=arr.join ("#"); // Specifies the delimiter as #Console.log (RESULTSEP); // Red#green#blue

The slice () method intercepts a subset of the elements in the current array to form a new array. (The intercepted part includes the beginning excluding the end) 

 Letarr=[1,2,3,4,5,6,7]; LetSlicearr=arr.slice (2,5);//number stands for index, starting from 0Console.log (arr);//[1, 2, 3, 4, 5, 6, 7]Console.log (Slicearr);//[3, 4, 5]            //The parameter is optional, starting with 0 if you do not write begin. Does not write end, it is truncated to the end of the array. //If begin is a negative number, it means to intercept from the penultimate element of the array, slice (-2) to intercept the 2nd element in the array to the last element (containing the last element). //if End is negative, it means that the penultimate element in the array ends the interception, and slice ( -2,-1) intercepts the 2nd element to the bottom 1th element (not including the last element) LetSlicearr=arr.slice ( -3,-1);
Console.log (Slicearr);//[5, 6]

The IndexOf () method returns the first index of an element equal to the specified value, or 1 if no such element is found;

 Letarr=["Red", "green", "blue", "white", "green"]; LetResult=arr.indexof ("Blue"); Console.log (result);//2 LetResult=arr.indexof ("Yellow"); Console.log (result);//-1
//The indexOf () method has an optional second parameter that indicates where to start the lookup. If the index value is greater than or equal to the array length, it is not found in the array and returns-1.
If a negative value is provided in the argument, it is used as an offset to the length of the array, that is, 1 is the search starting from the last element, and 2 means finding it starting from the bottom 2nd element, and so on.
Note: If a negative value is provided in the argument, it does not change its lookup order, and the lookup order is still the previous lookup array. If the index value after the offset is still less than 0, the entire array will be queried. Console.log (Arr.indexof ("Blue", 10));//-1Console.log (Arr.indexof ("Green", 2));//4Console.log (Arr.indexof ("Blue",-2));//-1Console.log (Arr.indexof ("Red",-10));//0

The LastIndexOf () method finds the index of an element equal to the specified element, starting at the last element of the array, and returns 1 if it is not found.

 Let's arr=["red", "green", "blue", "white", "Green"];console.log (Arr.lastindexof ("green")); // 4
// the 2nd parameter is the find location. By default, the length of the array is reduced by 1, which means that the entire arrays are looked up.
If the value is greater than or equal to the length of the array, the entire array is looked up. If negative, the forward offset of the end of the array is considered.
Even if the value is negative, the array will still look forward from the end. If the value is negative, the absolute is greater than the array length, then 1 is returned, that is, the array is not looked up. Console.log (Arr.lastindexof ("green", 1)); // 1console.log (Arr.lastindexof ("White",-2)); // 3

The ToString () method returns a string that has all the array elements combined

 let arr=[1,2,3,4,5];  let result=arr.tostring (); Console.log (arr); // [1, 2, 3, 4, 5]console.log (result); // 1,2,3,4,5

In addition, there are some iterative methods and methods of inheritance that are not mentioned here. (Due to the limited level and ability, if you have errors, please correct me)

Some common methods of arrays in JavaScript

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.