Detailed description of the new array method in ES5

Source: Internet
Author: User
Tags javascript array hasownproperty

First, preface-index

ES5 a lot of new things to know about our writing JavaScript will be a lot of help, such as the array of this piece, we may not need to rhythmic to for the loop.

The write array method is added in ES5, as follows:

    1. ForEach (JS v1.6)
    2. Map (JS v1.6)
    3. Filter (JS v1.6)
    4. Some (JS v1.6)
    5. Every (JS v1.6)
    6. IndexOf (JS v1.6)
    7. LastIndexOf (JS v1.6)
    8. Reduce (JS v1.8)
    9. Reduceright (JS v1.8)

Browser support

    • Opera 11+
    • Firefox 3.6+
    • Safari 5+
    • Chrome 8+
    • Internet Explorer +

For IE6-IE8 browsers that disappoint many times, the array prototype extension can implement all of the above functions, such as forEach methods:

For antique browsers, such as Ie6-ie8array.prototype." Function ") {  array.prototype.  /* implementation */};}   
Second one.
  1. ForEach
    forEachIs the most basic of the new array method, that is, traversal, loop. For example, the following example:

    [1, 2, 3, 4] . ForEach (alert); 

    This is equivalent to the following traditional for loop:

    Array = [4];  for (Array.Length; k < length; k++) {alert (array[k]);}   

    Array in ES5 new method, the parameters are all types, the default is the parameter function , which are the parameters? See below:

    [2,4].  ForEach (Console.log); //Results://1, 0, [1, 2, 3, 4]//2, 1, [1, 2, 3, 4]//3, 2, [1, 2, 3, 4]//4, 3, [1, 2,3, 4] /c20> 

    Obviously, forEach the callback in the method function supports 3 parameters, the 1th is the array contents of the traversal, the 2nd is the corresponding array index, and the 3rd is the array itself.

    Therefore, we have:

    [].foreach (function (value, index, array) {    //...});

    Compare the methods in jquery $.each :

    $.each ([], function (index, value, array) {    //...});

    Will find that the 1th and 2nd parameters are exactly the opposite, we have to pay attention to, do not remember the wrong. A similar approach is followed, for example $.map .

    Now, we can use forEach a slightly more complete example of showing off, array summation:

     var sum = 0;[ 1, 2, 3, 4]. ForEach (function (item, index, array) {console. Log (array[index] = = item); //true sum + = ITEM;}); alert (sum); //10            

    Further down, further, forEach in addition to accepting a mandatory callback function parameter, you can also accept an optional context parameter (change the pointer inside the callback function this ) (the 2nd parameter).

    Array.foreach (callback,[Thisobject])

    Examples are more illustrative of everything:

    var database = {  users: ["Zhang Yun", "Dancing Dogs", "Li Xiaolu"],  sendemail:function (user) {    if (this.isvaliduser (user)) {
         
          console.log ("Hello," + user);    } else {      Console.log ("Sorry," + user + ", you are not a family member")}  ,  isvaliduser:function (user) {    return/^/. Test (user);  }};/ /Give everyone legal mail Database.users.forEach (/  
          /database.users in person traverse  Database.sendemail,    //Send mail  Database               //Use database in place of the above marked red);  Results://Hello, Zhang Han Yun//Sorry, dancing dogs, you are not the family//Sorry, Li Xiaolu, you are not a clan   
         

    If this 2nd optional parameter is not specified, the global object is used instead (in the case of the browser window ), or even in strict mode undefined .

    In addition, foreach does not traverse the purely "official rates" element, such as the following example:

    Array = [array[//Remove 2alert (//"1,,3" alert (//But the length is still 3array. ) Just 1 and 3 pop up.     

    With all the rules in place, we can extend the simulation to IE6-IE8, as in the following code:

    For antique browsers, such as Ie6-ie8array.prototype." Function ") {  array.prototype.  Function (FN, context) {for (var k = 0, length = this.length; k < length; k++) {if (typeof fn = = = "function" &&am P Object.prototype.hasOwnProperty.call (this, k)) {Fn.call (context, this[k], K, this);}} };}

    Now take the "Zhang Yun" example above to measure the method of our expansion forEach , you may click here: Compatible with the Foreach method demo

    For example under IE7 browser:

  2. Map
    Here'smapNot the meaning of "map", but "mapping".[].map();Basic usage andforEachSimilar methods:

    Array.map (callback,[thisobject]);

    callbackThe parameters are similar:

    [].map (function (value, index, array) {    //...});

    mapThe function of the method is not difficult to understand, "mapping", that is, the original array is "mapped" into a corresponding new array. The following example is the value of the square:

    var data = [1, 2, 3, 4];var arrayofsquares = Data.map (function (item) {  //1, 4, 9,

    callbackNeed to have a return value, if not, just like this:

    var data = [1, 2, 3, 4];var arrayofsquares = Data.map (function () {}); Arrayofsquares.foreach (Console.log);

    As a result, as you can see, all the items in the array are mapped undefined :

    In practical use, we can make use of the map method to obtain the specific attribute values in the object array conveniently. For example, the following example is also the example of a compatible demo:

    var users = [  {name: "Zhang contains rhyme", "email": "[email protected]"},  {name: "Dancing Dogs",   "email": "[email protected]"},  {name: "Li Xiaolu",  //[email protected], [email protected], [email protected]

    Array.prototypeExtensions allow IE6-IE8 browsers to also support map methods:

    if (typeof Array.prototype.map! = "function") {  Array.prototype.map = function (FN, context) {    var arr = [];    if (typeof fn = = = "function") {      for (var k = 0, length = this.length; k < length; k++) {               Arr.push (Fn.call (Con Text, This[k], K, this));      }    }    return arr;  };}

    You can click here: Test demo with Map-compatible method

    The results show, for example, IE6 browser:

  3. Filter
    filterTo "filter", "Filter" means. Index Groupfilter, the new filtered array is returned. Usage andmapVery similar:

    Array.filter (callback,[thisobject]);

    filtercallbackfunction needs to return a Boolean true value or. If that's the false case true , congratulations, it's over! If false it is, only sing "I can only ruthlessly abandon you ...".

    May be questioned, must be Boolean worth it? We can simply test the next, as follows:

    var data = [0, 1, 2, 3];var arrayfilter = Data.filter (function (item) {    //[1, 2, 3]

    It can be seen that the return value is as weak as == true/false it is, and not necessarily returned === true/false .

    Therefore, we do not need to worry about whether the return value is purely Boolean (see the Black Code section below) when expanding for a low-version browser:

    if (typeof Array.prototype.filter! = "function") {  Array.prototype.filter = function (FN, context) {    var arr = [];    if (typeof fn = = = "function") {       for (var k = 0, length = this.length; k < length; k++) {          Fn.call (context, This[k], K, this) && Arr.push (This[k]);       }    }    return arr;  };}

    Then map you can click here for an example of how to filter the email: Test Demo with the filter method after compatibility

    The main test code is:

    var Emailszhang = users  //Get mail  . Map (function (user) {return user.email;})  //filter out the message at the beginning of the Zhang  . filter (function (email) {  //[email protected]  

    In fact, there are some syntactic sugars that can be achieved map+filter by the effect, known as "array Comprehensions". Currently, only the Firefox browser can be implemented, the display will not be pregnant:

    Zhangemails = [user.  Each (if (/^zhang/).  Test (user.  email)]; Console.log (//[[email protected]]        

  4. some
    somemeaning "certain" refers to whether "certain items" are eligible. With the followingeveryA good friend,everyIndicates whether "Every item" should be reliable. Use the following:

    Array.some (callback,[thisobject]);

    For example, the following simple use:

    var scores = [5, 8, 3, 10];var current = 7;function Higherthancurrent (score) {  return score > current;} if (Scores.some (higherthancurrent)) {  alert ("I've got it!") ");}

    The result pops up the "I Quasi" text. somerequires at least 1 values for callback the return true to be allowed. Obviously, 8 > 7 so the scores.some(higherThanCurrent) value is true .

    We can naturally use the forEach judgment, however, compared some to the lack of, only the return is some true no longer executed.

    The IE6-IE8 extension is as follows:

    if (typeof Array.prototype.some! = "function") {  Array.prototype.some = function (FN, context) {var passed = False;if (typeof fn = = = "function") {     for (var k = 0, length = this.length; k < length; k++) {  if (passed = = = True) break;  Passed =!! Fn.call (context, this[k], K, this);  }    } return passed;}  ;}

    So, we have a "I have the right" of the demo, you can click here: Compatible with the Some method after the demo

  5. Every
    somethe relationship with the basic friend is already a public secret, but also return a Boolean value, but every need every concubine to let me satisfied, otherwise-"bearer, dragged me out to chop!" ”

    IE6-IE8 extensions ( some compared to true and false swapped):

    if (typeof Array.prototype.every! = "function") {  Array.prototype.every = function (FN, context) {    var passed = tr UE;    if (typeof fn = = = "function") {       for (var k = 0, length = this.length; k < length; k++) {          if (passed = = = False) break;          Passed =!! Fn.call (context, this[k], K, this);      }    }    return passed;}  ;}

    Or the example, you can click here: whether every concubine let me satisfied with the demo

    if (Scores.every (higherthancurrent)) {  Console.log ("I've got it!") ");} else {  Console.log ("Somebody, pull out!" ");        }

    The result is:

  6. indexOf
    indexOfMethods have been used since ancient times in strings,string.indexOf(searchString, position)。 Array Here'sindexOfmethod is similar to this.

    Array.indexof (searchelement[, FromIndex])

    Returns an integer index value, if no match (strict match) is returned -1 . fromIndex Optional, means to start the search from this location, if the default or format is not required, using the default values 0 , I test under Firefox, I found that the use of string values is also possible, for example, "3" and 3 can be.

    -1 (not found because 5!== "5")

    Compatibility is handled as follows:

    if (typeof Array.prototype.indexOf! = "function") {  Array.prototype.indexOf = function (Searchelement, fromIndex) { C1/>var index =-1;    FromIndex = fromIndex * 1 | | 0;    for (var k = 0, length = this.length; k < length; k++) {      if (k >= fromIndex && this[k] = = = Searchelement ) {          index = k;          break;      }    }    return index;  };}

    One way down, obviously, it's your turn to demo, you can click here: Compatible with IndexOf method test Demo

    For IETester IE6:

  7. lastIndexOf
    lastIndexOfMethod andindexOfSimilar methods:

    Array.lastindexof (searchelement[, FromIndex])

    Just lastIndexOf start looking at the end of the string, not from the beginning. Another difference is that fromIndex the default value is array.length - 1 not 0 .

    IE6 and other browsers are tossing:

    if (typeof Array.prototype.lastIndexOf! = "function") {  Array.prototype.lastIndexOf = function (Searchelement, FromIndex) {    var index =-1, length = this.length;    FromIndex = fromIndex * 1 | | length-1;    for (var k = length-1; k >-1; k-=1) {        if (k <= fromIndex && this[k] = = = searchelement) {            index = K;            break;        }    }    return index;  };}

    Thus, there are:

    -1 (not found)

    Lazy, results view can be ruthlessly click here: LastIndexOf Test Demo

  8. Reduce
    reduceis introduced in JavaScript 1.8, Chinese meaning "reduction", "reduced". However, from a functional point of view, I personally can not be associated with the meaning of "reduction", but closer to the "iteration", "recursion (recursion)", rub, because the word is so close, will not be ECMA-262 5th the writer error is wrong ~ ~

    This method is more complex than the above methods and is used as follows:

    Array.reduce (callback[, InitialValue])

    callbackThe function accepts 4 parameters: the previous value, the current value, the index value, and the array itself. initialValueThe parameter is optional and represents the initial value. If specified, it is treated as the originally used value, and previous if the default, the first element of the array is used as the previous initial value, and the back row is current one initialValue less iteration than the value.

    var sum = [1, 2, 3, 4].reduce (function (Previous, current, index, array) {  //

    Description

      1. Because initialValue it does not exist, the previous first value is equal to the initial element of the array.
      2. Thus the current value is at the time of the first call 2 .
      3. The last two parameters are index values index and the array itself array .

    The following is the loop execution process:

    Initial Setup previous = InitialValue = 1, current = 2//First Iteration previous = (1 + 2) =  3, current = 3//second Iteration previous = ( 3 + 3) =  6, current = 4//Third Iteration previous = (6 + 4) =  Ten, current = undefined (exit)  

    With this reduce , we can easily achieve flattening of two-dimensional arrays:

    var matrix = [  [1, 2],  [3, 4],  [5, 6]];  Two-dimensional array flattening var flatten = matrix.reduce (function (Previous, current) {  //[1, 2, 3, 4, 5, 6] 

    Compatible processing IE6-IE8:

    if (typeof Array.prototype.reduce! = "function") {  Array.prototype.reduce = function (callback, initialvalue) {     var previous = InitialValue, k = 0, length = this.length;     if (typeof InitialValue = = = = "undefined") {        previous = this[0];        k = 1;     }         if (typeof callback = = = "function") {for      (k; k < length; k++) {         this.hasownproperty (k) && (previous = Callback (Previous, This[k], K, this));      }    }    return previous;}  ;}

    Then, test the integration, demo demo, you can click here: IE6-compatible reduce method test Demo

    IE6 browser results such as:

  9. Reduceright
    reduceRightWithreduceIn comparison, the usage is similar:

    Array.reduceright (callback[, InitialValue])

    The difference in implementation reduceRight is that it is implemented from the end of the array. Look at the following example:

    var data = [1, 2, 3, 4];var Specialdiff = data.reduceright (function (Previous, current, index) {  if (index = = 0) {
         
          return previous + current;  }  
          //0
         

    0How did the results get?
    We take a step-by-step look at Loop execution:

    Initial setting index = 3, previous = InitialValue = 4, current = 3//First Iteration index = 2, previous = (4-3) = 1, current = 2// Second iteration index = 1, previous = (1-2) =-1, current = 1//Third Iteration index = 0, previous = ( -1 + 1) = 0, current = undefined (fallback Out)  

    For the low-version browser to support this method, you can add the following code:

    if (typeof Array.prototype.reduceRight! = "function") {  Array.prototype.reduceRight = function (callback, InitialValue) {    var length = this.length, k = length-1, previous = InitialValue;    if (typeof InitialValue = = = = "undefined") {        previous = this[length-1];        k--;    }    if (typeof callback = = = "function") {for       (k; k >-1; k-=1) {                    this.hasownproperty (k) && (previous = cal Lback (Previous, This[k], K, this));       }    }    return previous;}  ;}

    You can click here: Reduceright easy to use demo

    Compare the results under the Firefox browser and the IE7 browser:

Third, the further application

We can also apply the above array methods to other objects.

For example, we use foreach to traverse DOM elements.

var eledivs = document.getelementsbytagname ("div"); Array.prototype.forEach.call (Eledivs, function (div) {    console.log ("The div class name is:" + (Div.classname | | "Empty"));});

You can output all div the class names of the page, you can click here: Array New method foreach traversal Dom demo

The results are as follows, IE6, demo results:

And so many other class array applications.

Four, finally a little bit

This article for the low version of IE extension of the array method I have merged into a JS, you can gently right here or download or view: Es5-array.js

All of the above methods of non-IE extension are written according to their own understanding, although the test, there will inevitably be details omitted, welcome to point out.

Reference article:
JavaScript array "extras" in detail
Array.foreach

Original article, reprint please indicate from Zhang Xin Xu-Xin space-Xin Life [http://www.zhangxinxu.com]
This address: http://www.zhangxinxu.com/wordpress/?p=3220

Detailed description of the new array method in ES5

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.