A detailed description of the Array object method in JS

Source: Internet
Author: User

Operating Method : concat () Slice () splice ()

The Concat () method can create a new array based on all the items in the current array. Specifically, this method creates a copy of the current array, adds the received parameter to the end of the copy, and returns the newly constructed array. If there are no arguments, copy the current array and return the copy. If the parameter is one or more arrays, each item in the array is added to the result array. If the parameter is not an array, the parameter value is added to the end of the array.

        var colors = [' red ', ' green ', ' Blue '];         var colors2 = Colors.concat (' Yellow ', [' Gray ', ' black ']);        alert (colors); // Red,green,blue        alert (COLORS2); // Red,green,blue,yellow,gray,black    

The slice () method can create a new array based on one or more items in the current array. You can accept 1 or 2 parameters, that is, to return the starting and ending positions of an item. A parameter, slice () returns all items starting at the specified position of the parameter to the end of the current array. Two parameters, the method returns the entry between the start and end positions, but not the ending position. Note: the slice () method does not affect the original array.

If the slice () method passes a negative number, the corresponding position is determined by the array length plus the change. For example, calling Slice ( -2,-1) on an array containing 5 items is the same as calling slice (3,4). If the end position is less than the start position, an empty array is returned.

        var colors = [' red ', ' green ', ' blue ', ' yellow ', ' gray '];         var colors2 = colors.slice (1);         var colors3 = colors.slice (3,4);         var colors4 = Colors.slice ( -2,-1);        alert (colors2); // Green,blue,yellow,gray        alert (COLORS3); // Yellow        alert (COLORS4); // Yellow

The splice () method should be the most powerful method in the array, and splice () mainly inserts an item into the middle of the array, using the method in 3:

Delete: You can delete any number of items, just pass in two parameters: the location of the first item to delete and the number of items to delete. For example, splice (0,2) deletes the first two items in the array.

Insert: You can insert any number of items to a specified location, providing only three parameters: the starting position, 0 (the number of bits to delete), and the value to insert. If you want to insert more than one item, you can continue to pass in fourth, five, any number of items. For example, splice (2,0, ' red ', ' green ') will insert the string ' red ', ' green ' from the current array position 2.

Replace: You can insert any number of items to the specified location and delete any number of items at the same time. You only need to specify three parameters: the starting position, the number of items to delete, and any number of items to insert. The number of items inserted does not have to be equal to the number of items deleted. For example, splice (2,1, ' red ', ' green ') will delete the current array position 2, and then insert the string ' red ', ' green ', starting at position 2.

The splice () method always returns an array that contains the items removed from the original array (if no items were deleted to return an empty array).

        varcolors = [' red ', ' green ', ' blue ']; varremoved = Colors.splice (0,1);//Delete First itemalert (colors);//Green,bluealert (removed);//Redremoved = Colors.splice (1,0, ' yellow ', ' gray ');//Insert an item from the beginning of a positionalert (colors);//Green,yellow,gray,bluealert (removed);//Empty Arrayremoved = Colors.splice ("Red", ' white ');//Insert 2 items from the beginning of a position, delete 1 itemsalert (colors);//Green,red,white,gray,bluealert (removed);//Yellow

Location Method:indexOf () lastIndexOf ()

Both methods receive two parameters: the item to find, and, optionally, the index at which to find the start position. where indexof () is searched backwards from the beginning of the array, lastIndexOf () looks forward from the end of the array. Both methods return the position of the item to find in the array, and no return-1 is found. The strict equality operator is used when comparing the first argument to each item in the array, that is, the items that are required to be found must be strictly equal (as with the = = =).

        var numbers = [1,2,3,4,5,4,3,2,1];        Alert (Numbers.indexof (3)); // 2        Alert (Numbers.lastindexof (3)); // 6        Alert (Numbers.indexof (3,3)); // 6        Alert (Numbers.lastindexof (3,3)); // 2        Alert (Numbers.indexof (6)); // -1        Alert (Numbers.indexof (1)); // 0

Conversion Method:toString () tolocalestring () valueOf ()

Calling the ToString () method returns a comma-delimited string that is stitched together as a string of each value in the array. The ToString () method of each item is called in order to create this string. ValueOf () returns an array.

Calling tolocalestring () usually returns the same value as the ToString () valueOf () method, but it is not always the case. It creates a comma-delimited string of array values. Unlike the other two methods, this time to get the value of each item, the toLocaleString () method for each item is called, not the ToString () method.

        varcolors = [' red ', ' black ', ' green ']; alert (colors);//Red,black,greenAlert (colors.tostring ());//Red,black,greenAlert (colors.valueof ());//Red,black,green        varPerson1 ={toString:function(){              return' Zhangsan '; }, toLocaleString:function(){                return' Localzhangsan ';        }        }; varPerson2 ={toString:function(){              return' Lisi '; }, toLocaleString:function(){                return' Locallisi ';        }        }; varperson =[Person1,person2]; alert (person);//Zhangsan,lisiAlert (person.tostring ());//Zhangsan,lisiAlert (person.tolocalestring ());//Localzhangsan,locallisi

The array-integrated ToString (), tolocalestring (), ValueOf () methods return array items by default as a comma-delimited string. If you use the Join () method, you can use a different delimiter to construct the string. If you do not pass any value to the join () method or pass in undefined, use a comma as the delimiter.

        var colors = [' red ', ' black ', ' green '];        alert (colors); // Red,black,green        Alert (Colors.join (', ')); // Red,black,green        Alert (colors.join (' | | ')); // red| | black| | Green        alert (Colors.join ());   red,black,green        alert (colors.join (undefined));   Red,black,green

Stack method : Push () Pop ()

The stack is a LIFO (Last-in-first-out, LIFO) data structure. The insert (called Push-in) and the remove (called eject) in the stack occur only in one place-the top of the stack. The ECMAScript array specifically provides the push () and Pop () methods to implement a stack-like behavior.

The push () method can receive any number of arguments, add them individually to the end of the array, and return the modified length. The Pop () method removes the last item from the end of the array, reduces the length value of the array, and then returns the item that was removed.

        var New Array ();         var count = Colors.push (' Red ', ' black ', ' green ');        alert (count); // 3        var count = Colors.push (' blue ');        alert (count); // 4        var item = colors.pop ();        alert (item); // Blue        alert (colors.length); // 3

Queue method : Shift () Unshift ()

The access rules for the

Queue data structure are FIFO (first-in-first-out, first-in, FIFO). The queue adds items at the end of the list, removing items from the front end of the list. The shift () method moves the first item in the array and returns the item, minus 1 of the length. Using the shift () and push () methods together, you can use arrays as you would with queues.

 var  colors = new   Array ();  var  count = Colors.push (' Red ', ' black ', ' green ')        ); alert (count);  // 3  var  count = Colors.push (' Blue ' ); alert (count);  // 4  var  item = Colors.shift (); alert (item);  // red  alert (colors.length); // 3  

The

Unshift () method, in contrast to the shift () method, adds any number of items to the front of the array and returns the length of the new array. Therefore, using the Unshift () and Pop () methods simultaneously, you can simulate the queue in the opposite direction and remove the item at the end of the array.

        var New Array ();         var count = Colors.unshift (' Red ', ' black ', ' green ');        alert (count); // 3        var count = Colors.unshift (' blue ');        alert (count); // 4        var item = colors.pop ();        alert (item); // Green        alert (colors.length); // 3

Reorder Method:reverse () sort ()

The reverse () method reverses the order of the array items.

        var values = [1,2,3,4,5];        Values.reverse ();        alert (values); // 5,4,3,2,1

The function of this reverse () is straightforward, but not flexible enough, so there is a sort () method. By default, the sort () method arranges array items in ascending order-that is, the smallest value is at the front and the largest value is the last. In order to implement sorting, the sort () method invokes the ToString () method of each array item, and then compares the resulting string. Even if each item in the array is a numeric value, the sort () comparison is also a string.

        var values = [0,1,5,10,15];        Values.sort ();        alert (values); // 0,1,10,15,5

Obviously, this sort of approach is not the best scenario in many cases. So the sort () method can receive a comparison function as a parameter so that we specify which value is in front of which value.

The comparison function receives two parameters, returns a negative number if the first argument should precede the second argument, returns 0 if the two arguments are equal, or returns a positive number if the first argument should be after the second argument. Here is a simple comparison function:

        varvalues = [0,1,5,10,15];        Values.sort (Compare); alert (values);//0,1,5,10,15        functionCompare (value1,value2) {if(Value1 <value2) {                return-1; }Else if(Value1 >value2) {                return1; }Else{                return0; }        }

The return values of the reverse () and sort () methods are sorted arrays.

Iterative method:every () filter () ForEach () map () some ()

ECMASCRIPT5 defines 5 iterative methods for an array. Each method receives two parameters: the function to run on each item and, optionally, the scope object that runs the function-the value that affects this. The functions passed in these methods receive three parameters: the value of the array item, the position of the item in the array, and the group object itself. The return value after execution of this function may not affect the return value of the access.

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

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. no return value.

Map (): Each item in the array runs the given function, returning an array consisting of the results of each function call.

Some (): Each item in the age group runs the given function, and returns TRUE if the function returns true for either item.

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

       varnumbers = [0,1,5,10,15]; varEveryresult = Numbers.every (function(Item,index,array) {return(item>2); }) alert (Everyresult);//false        varSomeresult = Numbers.some (function(Item,index,array) {return(item>2);        }); alert (someresult);//true        varFilterresult = Numbers.filter (function(Item,index,array) {return(item>2);        }); alert (filterresult);//5,10,15        varMapresult = Numbers.map (function(Item,index,array) {return(item*2);        }); alert (mapresult);//0,2,10,20,30Numbers.foreach (function(Item,index,array) {//perform certain actions});

reduction Method:reduce () reduceright ()

ECMASCRIPT5 also adds 2 ways to reduce the array: reduce () and reduceright (). Both methods iterate over all the items of an algebraic group and then build a value that is ultimately returned. where the reduce () method starts with the first item in the array and traverses through to the end. The Reduceright () method, starting with the last item in the array, iterates forward to the first item.

Both methods receive two parameters: a function that is called on each item and (optionally) the initial value to reduce the base. The pass to reduce () Reduceright () function receives 4 parameters: the previous value, the current value, the index of the item, and the array object. Any value returned by this function will be automatically passed to the next item as the first argument. The first iteration occurs on the second item of the array, so the first parameter is the first item of the array, and the second is the second item of the array.

         var numbers = [0,1,5,10,15];         var sum = numbers.reduce (function(prev,cur,index,array) {            return prev +  cur;        })        alert (sum); //  to

The first time the callback function is executed, Prev is 0,cur is 1. The second time, Prev is 1 (0+1), and Cur is 3 (the third item in the array). This process will continue to access each item of the array once and finally return the result.

The Reduceright () method acts similarly, except in the opposite direction.

        var numbers = [0,1,5,10,15];         var sum = numbers.reduceright (function(prev,cur,index,array) {            return prev + cur;        })        alert (sum); //  to

In the above example, the first time the callback function is executed, Prev is 15,cur is 10. The end result is the same.

Reference JavaScript Advanced Programming (Third edition)

  

A detailed description of the Array object method in JS

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.