Common methods for JavaScript arrays

Source: Internet
Author: User

Determine if an object is an array: instanceof, Array.isarray ()

You can use the instanceof operator for a Web page or for a global scope.

if instanceof Array) {  // Determine if value is an array     }

instanceof Operator It assumes that there is only one global execution environment, and if the page contains more than one frame, use the ECMAScript5 new Array.isarray () method.

if (Array.isarray (value)) {// Determine if value is an array }

The browsers supported by the Array.isarray () method are ie9+, Firefor 4+, safari5+, Opera 10.5+, and Chrome.

If you want to examine the array in a browser that does not implement this method, use:

if (Object.prototype.toString.call (value) = = "[Object Array]") {}
Convert an array to a string: toLocaleString (), toString (), ValueOf (), join ()
var test=[' A ', ' B ', ' C '];alert (test.tostring ()); // a,b,calert (test.tolocalestring ()); // a,b,calert (test.valueof ()); // a,b,calert (test); // a,b,c default call to ToString () method alert (Test.join (', ')); // a,b,calert (test.join (' | ')); // A|b|c
Adding and removing an array element method: Push (), pop (), Unshift (), Shift ()

The push () method can accept any number of arguments , add them to the end of the array one by one, and return the array's modified array length .

The pop () method removes the last item from the end of the array, and then returns the item that was removed.

The unshift () method adds any number of arguments to the front of the array and returns the new array length .

The shift () method moves the first item in the array and returns the item that is removed .

var test=[]; var count = Test.push (' A ', ' B '); // Add Count =test.push (' C ') one at the end of the array , and alert (count); // 3alert (test); //

var item = test.pop (); alert (item); // Calert (test.length); // 2
Sort by: Reverse () and sort ()

The reverse () method reverses the array-item smoothing, manipulating the array itself .

The sort () method arranges array items by default in ascending order, manipulating the array itself .

var test=[1,2,3,4,5];test.reverse (); alert (test); // 5,4,3,2,1 var test2=[0,1,5,10,15];test2.sort (); alert (test2); //     the 0,1,10,15,5 sort () method invokes the ToString () method of each array item, comparing the string to determine the sort. So here sort of is string sort

The sort () method can also pass in a comparison function.

The comparison function returns a negative number before the first argument should precede the second, and returns 0 if the two arguments are equal, and a positive number after the first argument, which should precede the second one.

function Compare (value1,value2) {    if(value1<value2) {        return -1;    } Else if (value1>value2) {        return 1;    } Else {         return 0;     }      }     var test=[0,1,5,10,15];test.sort (Compare); alert (test); // 0,1,5,10,15   
Operating methods: Concat (), slice (), splice ()

The concat () method is used to concatenate two or more arrays. The method does not alter the existing array, but only returns a copy of the concatenated array. Returns a new array.

varA = [A.];alert (A.concat (4,5));//1,2,3,4,5vararr =NewArray (3) arr[0] = "George"arr[1] = "John"arr[2] = "Thomas"varARR2 =NewArray (3) arr2[0] = "James"arr2[1] = "Adrew"arr2[2] = "Martin"alert (Arr.concat (ARR2));//George,john,thomas,james,adrew,martinvararr =NewArray (3) arr[0] = "George"arr[1] = "John"arr[2] = "Thomas"varARR2 =NewArray (3) arr2[0] = "James"arr2[1] = "Adrew"arr2[2] = "Martin"varARR3 =NewArray (2) arr3[0] = "William"arr3[1] = "Franklin"alert (Arr.concat (ARR2,ARR3))//George,john,thomas,james,adrew,martin,william,franklin

The Slice () method returns the selected element from an existing array. Returns a new array containing elements from start to end (excluding the element) from the Arrayobject.

var test =[' A ', ' B ', ' C ', ' d ', ' e ']; var arr1=test.slice (1); var arr2=test.slice (1,4); alert (arr1); // b,c,d,ealert (ARR2); // b,c,d

The Splice () method adds/Deletes an item to/from the array, and then returns the item that was deleted. manipulate the array itself .

First parameter: Start position, second parameter: number of intercepts, third parameter: new element appended.

//DeletevarTest=[' A ', ' B ', ' C '];varRemoved=test.splice (0,1)//Delete First itemalert (test);//B,calert (removed);//a returns the item that was deleted//InsertvarTest2=[' A ', ' B ', ' C '];varRemoved2=test2.splice (1,0, ' d ', ' e ')//Insert D,e starting from position 1alert (test2);//A,d,e,b,cAlert (REMOVED2)//Empty Array//ReplacevarTest3=[' A ', ' B ', ' C '];varRemoved3=test3.splice (the "d ', ' e ')//Insert D,e starting from position 1alert (TEST3);//A,d,e,cAlert (REMOVED3)//b
Location method: IndexOf (), LastIndexOf ()

ECMASCRIPT5 provides methods to support browsers: ie9+, Firefox, Safari, Opera 9.5+, Chrome

The indexOf () method returns the position of the first occurrence of a specified string value in a string.

The lastIndexOf () method returns the location of the last occurrence of a specified string value, which is searched from behind at the specified position in a string.

A parameter: Represents the value to find, returns the index position (starting at 0), two parameters: the first parameter represents the starting position, and the second parameter represents the value to find.

var numbers=[1,2,3,4,5,4,3,2,1];alert (Numbers.indexof (4)); // 3Alert (Numbers.lastindexof (4)); // 5 Alert (numbers. IndexOf (bis)); // 5alert (numbers.lastindexof (bis)); // 3
Iterative methods: Every (), filter (), ForEach (), map (), some ()

ECMASCRIPT5 provides methods to support browsers: ie9+, Firefox, Safari, Opera 9.5+, Chrome

every (): Runs the given function for each item in the array, and returns True if the function returns true for each item.

filter (): Each item in an array runs the given function, and returns a list of items that are true of the function.

ForEach (): Runs the given function for each item in the array, and the method does not return a value .

map (): Each item in the array runs the given function, returning an array that consists of the results of each function call .

some (): Runs the given function for each item in the array, and returns True if the function returns true for either item.

None of the above functions will modify the values contained in the array.

varnumbers=[1,2,3,4,5,4,3,2,1];//every ()varEveryresult=numbers.every (function(Item,index,array) {return(item>2); }) alert (Everyresult);//false//some ()varSomeresult=numbers.some (function(Item,index,array) {return(item>2); }) alert (Someresult);//true//filter ()varFilterresult=numbers.filter (function(Item,index,array) {return(item>2); }) alert (Filterresult);//[3,4,5,4,3]//map ()varMapresult=numbers.map (function(Item,index,array) {return(item*2); }) alert (Mapresult);//[2,4,6,8,10,8,6,4,2]//ForEach ()Numbers.foreach (function(Item,index,array) {//no return value for execute Operation}) 
Merge method: Reduce (), reduceright ()

ECMASCRIPT5 provides methods to support browsers: ie9+, Firefox, Safari 4+, Opera 10.5+, Chrome

The two methods will iterate over the algebraic group so the item is then constructed with a final return value. The reduce () method starts with the first item in the array, and the Reduceright () method starts at the end of the array.

var values=[1,2,3,4,5]; var sum=valuse.reduce (function(prev,cur,index,array) {         prev+cur;}); alert (sum); //  the

Common methods for JavaScript arrays

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.