ES5 new Features: Understanding the 9 + APIs enhanced in Array

Source: Internet
Author: User

To make it easier to manipulate the array in JS, the ES5 specification adds 9 methods to the array's prototype, namely foreach, filter, map, reduce, reduceright, some, every, indexOf, and LastIndexOf, this article will explain these methods in detail, and the prototype extension of each method to be compatible with browsers that do not support ES5.

ForEach (Callback[,thisarg])

Before ES5, we could iterate through the array in the for and for in two ways, and ES5 introduced a new method, foreach, to make the array traversal more concise, the foreach needs to pass 2 parameters, the first parameter is the callback function, is the required parameter, the second argument is an object, Used to change the this point in the callback, which is an optional parameter.

var arr = [' A ', ' B ', ' C '];arr.foreach (function (v,i,r) {    console.log (v,i,r);}) ->a 0 ["A", "B", "C"]b 1 ["A", "B", "C"]c 2 ["A", "B", "C"]

As can be seen from the output results, 3 parameters are passed in callback v,i,r representing the current element, the current position, and the array object, respectively. And look at the example of using Thisarg:

var obj = {   Print:function (A, b) {       console.log (A, b);   }}; var arr = [' A ', ' B ', ' C '];arr.foreach (function (v,i,a) {   this.print (v,i);},obj);

When Thisargs is not passed, the this in callback points to the Window object, and when Thisarg is passed, this in callback points to thisarg, so the purpose of this parameter is to change this point in the callback function.

For browsers that do not support ES5, we can simply extend the foreach to be compatible with older browsers:

if (! Array.prototype.forEach) {    Array.prototype.forEach = function (callback,thisarg) {for        (var i=0;i< this.length;i++) {            //when Thisarg is undefined, the JS engine callback.call the window as its caller            (Thisarg,this[i],i, This.tostring ());}}}    

Filter (Callback[,thisarg])

Filter is the meaning of ' filtering ', so the function of this method is to return a new array matching the filter, which receives two parameters callback and Thisarg, callback is also a callback function, mainly for the element to match the conditions, As in Thisarg and foreach, the Thisarg function is not repeated here, as shown in the following example:

var arr = ["A", "B", "A", "C"];var newArr = Arr.filter (function (item) {     return item = = = "A";});       NEWARR, ["A", "a"]

The code is very simple, one can see that when there is no filter, in order to achieve this function, we have to create an empty array, the matching elements are then push in, and now do not need so much trouble, we look at the filter extension:

if (! Array.prototype.filter) {    Array.prototype.filter = function (callback, thisarg) {        var temp = [];        for (var i = 0; i < this.length; i++) {           if (Callback.call (Thisarg,this[i])) {               //If callback returns True, the element conforms to the filter condition, Press the element into temp               Temp.push (this[i]);}        }        return temp;}    }

Map (Callback[,thisarg])

The role of map is to process the original array and return it as a new array, the method also receives two parameters, callback is the callback function for the array processing, THISARG and the same as above. Let's look at a simple example:

var arr = [   {w:10,h:10},//define length and width   {w:15,h:20},   {W:12,h:12}];var NEWARR = Arr.map (function (item) {   // Calculates the area based on the length and width and assigns the value to the new property areas    Item.Area = ITEM.W * ITEM.H;   return item;}); Newarr[0]-> {w:10, h:10, area:100}

As you can see, Newarr returns an array of objects that have the Area property added. This method is very useful, in general, when an AJAX request is returned, we have to filter and check its result set, then the map comes in handy. Let's see if the map is extended for compatibility:

if (! Array.prototype.map) {   Array.prototype.map = function (callback, thisarg) {       var temp = [];       for (var i = 0; i < this.length; i++) {           var newitem = Callback.call (Thisarg,this[i]);           Temp.push (NewItem); Press the new element returned by callback into temp       }       return temp;}   }

Reduce (Callback[,initialvalue])

Reduce has a ' reduced ' meaning here, so what does reduce mean? Take a look at the more official explanation: The method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value. You slowly realize it, we first see how to use it, with more natural to understand:

var arr = [1,2,3,4];var NEWARR = Arr.reduce (function (Previousvalue, CurrentValue, Currentindex, array) {    Console.log (Previousvalue, currentvalue,currentindex);    return previousvalue + CurrentValue;}); 1 2 3 4 3NEWARR-10

As can be seen from the running results, reduce realizes the accumulation function of array elements, reduce receives 4 parameters, Previousvalue is the result of the last callback return, CurrentValue is the current element, Currentindex is the current element position, and array is the current one. The Previousvalue initial value is the first element of the array, which iterates through the 2nd element. Let's see what the hell InitialValue is:

var arr = [1,2,3,4];var NEWARR = Arr.reduce (function (Previousvalue, CurrentValue, Currentindex, array) {    Console.log (Previousvalue, currentvalue,currentindex);    return Previousvalue + currentvalue;},100), 1 0101 2 1103 3 2106 4 3NEWARR, 110

From the running results, the InitialValue parameter specifies the initial value of the previousvalue, and more importantly, the array is traversed from the 1th position, instead of starting at the 2nd position. Now look back and compare these two examples, I'm sure you will understand the role of reduce. The following extension to reduce will solidify your understanding of reduce:

if (! Array.prototype.reduce) {   Array.prototype.reduce = function (callback, initialvalue) {        var previousvalue = InitialValue | | this[0];//If you do not specify a intialvalue, the default is the first element of the array        //If you do not specify initialvalue,i to traverse from 1, or 0 to start traversing for        (var i = InitialValue? 0:1; i < this.length; i++) {            //previousvalue accumulates the result of each return            Previousvalue = Callback (Previousvalue, this[i],i,this.tostring ());        }        return previousvalue;}    }

Reduceright (Callback[,initialvalue])

Unlike reduce, the only difference is that Reduceright is the element that iterates through the array from right to left.

some (Callback[,thisarg])

Some is ' some, some ' meaning, so some's role is to detect every element in the array, and when callback returns true, it stops traversing and returns true, so the description seems somewhat abstract, see the code, everything in the code:

var arr = [1, 2, 3, 4];var result = Arr.some (function (item, index, array) {    Console.log (item, index, array);    return item > 2;}); 1 0 [1, 2, 3, 4] 2 1 [1, 2, 3, 4] 3 2 [1, 2, 3, 4] restule-True

From the running results, some detects the entire array, as long as an element in Arr meets the criteria item>2 stops detection and traversal, and returns true to indicate that the target was detected. This is a bit similar to our use of the break language in the For loop, and you should understand some's role now! The following extensions to some will help you understand some:

if (! Array.prototype.some) {   Array.prototype.some = function (callback, Thisarg) {for        (var i = 0; i < this.length; i++) {           if (Callback.call (thisarg,this[i],i,this.tostring ())) {               return true;//callback returns True, jumps out of the loop, and returns True           }        } return        false;//a qualified none detected, return False    }}

every (Callback[,thisarg])

Every is ' every ' meaning, compared to some, every to the detection of elements more stringent, that every what is to do, see the code will know:

var arr = [1, 2, 3, 4];var result = Arr.every (function (item, index, array) {    Console.log (item, index, array); 
   return Item < 3;}); 1 0 [1, 2, 3, 4] 2 1 [1, 2, 3, 4] 3 2 [1, 2, 3, 4] result--false

From the running results, when the 3rd element is detected, Item<3 is false, stop detection, and return false, indicating that every in the detection element, each element must meet the criteria item<3, if there is a non-conformance on the stop detection, and return false, ( PS: You can test the result of running item<5, the return value must be true). What is the every in the end? When a For loop uses the break statement, we want to know if the for loop is performing properly, we usually judge by detecting the index i==arr.length in for, so every is here. Let's look at the extension for the Every method:

if (! Array.prototype.every) {   Array.prototype.every = function (callback, Thisarg) {for        (var i = 0; i < this.length ; i++) {           if (!callback.call (thisarg,this[i],i,this.tostring ())) {               return false;//detects non-conforming elements, jumps out of the loop, and returns false           }        }        return true; All elements are eligible, return True    }}

IndexOf and LastIndexOf

These two methods are similar to the indexof and LastIndexOf in the string class, and I believe you are familiar with the two methods, so there is not much to explain here.

ES5 new Features: Understanding the 9 + APIs enhanced in Array

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.