Detailed description of Array extensions in Javascript

Source: Internet
Author: User
Tags javascript array

Array extensions in Javascript generally start with the object itself. Here we will introduce some items in the Array object. For example, indexOf is the index of the returned element in the Array, and-1 is returned if no element exists.

Recently I read something in developer.mozilla.org and found that it has added many generic methods to the Array Extension to catch up with Prototype's enthusiasm.

IndexOf

Returns the index of the element in the array. If no index exists,-1 is returned. Similar to the indexOf method of string.

If other browsers do not implement this method, use the following code for compatibility:

 
 
  1. Array.prototype.indexOf = function(el, start) {   
  2.     var startstart = start || 0;   
  3.     for ( var i=0; i < this.length; ++i ) {   
  4.         if ( this[i] === el ) {   
  5.             return i;   
  6.        }   
  7.     }   
  8.     return -1;   
  9. };  
  10. var array = [2, 5, 9];   
  11. var index = array.indexOf(2);   
  12. // index is 0   
  13. index = array.indexOf(7);   
  14. // index is -1  
LastIndexOf

Similar to the lastIndexOf method of string.

If other browsers do not implement this method, use the following code for compatibility:

 
 
  1. Array.prototype.lastIndexOf = function(el, start) {   
  2.     var startstart = start || this.length;   
  3.     if ( start >= this.length ) {   
  4.         start = this.length;   
  5.     }   
  6.    if ( start < 0 ) {   
  7.          start = this.length + start;   
  8.     }   
  9.    for ( var i=start; i >= 0; --i ) {   
  10.         if ( this[i] === el ) {   
  11.           return i;   
  12.       }   
  13.    }   
  14.     return -1;   
  15. };  
ForEach

Similar each methods are implemented in various libraries.

If other browsers do not implement this method, use the following code for compatibility:

 
 
  1. Array.prototype.forEach = function(fn, thisObj) {   
  2.     var scope = thisObj || window;   
  3.     for ( var i=0, j=this.length; i < j; ++i ) {   
  4.         fn.call(scope, this[i], i, this);   
  5.    }   
  6. };  
  7. function printElt(element, index, array) {   
  8.     print("[" + index + "] is " + element); // assumes print is already defined   
  9. }   
  10. [2, 5, 9].forEach(printElt);   
  11. // Prints:   
  12. // [0] is 2   
  13. // [1] is 5   
  14. // [2] is 9  

Every

If each element in the array can pass the test of the given function, true is returned, whereas false is returned. In other words, the given function must also return true and false.

If other browsers do not implement this method, use the following code for compatibility:

 
 
  1. Array.prototype.every = function(fn, thisObj) {   
  2.    var scope = thisObj || window;   
  3.     for ( var i=0, j=this.length; i < j; ++i ) {   
  4.         if ( !fn.call(scope, this[i], i, this) ) {   
  5.             return false;   
  6.         }   
  7.     }   
  8.     return true;   
  9. };  
  10. function isBigEnough(element, index, array) {   
  11.   return (element >= 10);   
  12. }   
  13. var passed = [12, 5, 8, 130, 44].every(isBigEnough);   
  14. console.log(passed)   
  15. // passed is false   
  16. passed = [12, 54, 18, 130, 44].every(isBigEnough);   
  17. // passed is true   
  18. console.log(passed)  
Some

Similar to the every function, but returns true if one test passes the given function.

If other browsers do not implement this method, use the following code for compatibility:

 
 
  1. Array.prototype.some = function(fn, thisObj) {   
  2.     var scope = thisObj || window;   
  3.     for ( var i=0, j=this.length; i < j; ++i ) {   
  4.         if ( fn.call(scope, this[i], i, this) ) {   
  5.             return true;   
  6.        }   
  7.     }   
  8.     return false;   
  9. };  
  10. function isBigEnough(element, index, array) {   
  11.   return (element >= 10);   
  12. }   
  13. var passed = [2, 5, 8, 1, 4].some(isBigEnough);   
  14. // passed is false   
  15. passed = [12, 5, 8, 1, 4].some(isBigEnough);   
  16. // passed is true 
Filter

Place the elements that meet the conditions in a new array and return them.

If other browsers do not implement this method, use the following code for compatibility:

 
 
  1. Array.prototype.filter = function(fn, thisObj) {   
  2.     var scope = thisObj || window;   
  3.    var a = [];   
  4.     for ( var i=0, j=this.length; i < j; ++i ) {   
  5.        if ( !fn.call(scope, this[i], i, this) ) {   
  6.             continue;   
  7.        }   
  8.         a.push(this[i]);   
  9.     }   
  10.    return a;   
  11. };  
  12. function isBigEnough(element, index, array) {   
  13.   return (element <= 10);   
  14. }   
  15. var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);  
Map

Let each element in the array call the given function, and then put the result into the new array to return ..

If other browsers do not implement this method, use the following code for compatibility:

 
 
  1. Array.prototype.map = function(fn, thisObj) {   
  2.     var scope = thisObj || window;   
  3.     var a = [];   
  4.    for ( var i=0, j=this.length; i < j; ++i ) {   
  5.        a.push(fn.call(scope, this[i], i, this));   
  6.     }   
  7.     return a;   
  8. };  
  9. var numbers = [1, 4, 9];   
  10. var roots = numbers.map(Math.sqrt);   
  11. // roots is now [1, 2, 3]   
  12. // numbers is still [1, 4, 9] 
Reduce

Let the array element call the given function in sequence and return a value. In other words, the returned value must be used for the given function.

If other browsers do not implement this method, use the following code for compatibility:

 
 
  1. Array.prototype.reduce = function(fun /*, initial*/)   
  2. {   
  3.   var len = this.length >>> 0;   
  4.  if (typeof fun != "function")   
  5.     throw new TypeError();   
  6.  if (len == 0 && arguments.length == 1)   
  7.    throw new TypeError();   
  8.  var i = 0;   
  9.   if (arguments.length >= 2){   
  10.     var rv = arguments[1];   
  11.   } else{   
  12.    do{   
  13.      if (i in this){   
  14.        rv = this[i++];   
  15.         break;   
  16.      }   
  17.     if (++i >= len)   
  18.         throw new TypeError();   
  19.    }while (true);   
  20.   }   
  21.   for (; i < len; i++){   
  22.    if (i in this)   
  23.      rv = fun.call(null, rv, this[i], i, this);   
  24.   }   
  25.   return rv;   
  26. };  
  27. var total = [0, 1, 2, 3].reduce(function(a, b){ return a + b; });   
  28. // total == 6 
Original article title: javascript Array Extension

Link: http://www.cnblogs.com/rubylouvre/archive/2009/09/20/1570461.html

  1. What is JSON? Data format prepared for JavaScript
  2. 10 most commonly used JavaScript udfs
  3. Some extended thoughts on loading JavaScript events
  4. Summary of JavaScript usage: From BOM and DOM
  5. How ExtJS works on Android Simulators

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.