Skip to content

Instantly share code, notes, and snippets.

@yangg
Created September 7, 2012 02:37
Show Gist options
  • Select an option

  • Save yangg/3662658 to your computer and use it in GitHub Desktop.

Select an option

Save yangg/3662658 to your computer and use it in GitHub Desktop.

Revisions

  1. yangg created this gist Sep 7, 2012.
    47 changes: 47 additions & 0 deletions array.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array

    /*
    * Implemented in JavaScript 1.6
    */
    Array.prototype.forEach = Array.prototype.forEach || function(fun /*, thisp*/) {
    var len = this.length >>> 0;
    if(typeof fun != 'function') { throw new TypeError(fun + ' is not a function'); }
    for(var thisp = arguments[1], i = 0; i < len; i++) {
    if(i in this) {
    fun.call(thisp, this[i], i, this);
    }
    }
    };

    /*
    * Implemented in JavaScript 1.6
    */
    Array.prototype.indexOf = Array.prototype.indexOf || function(elt /*, from*/) {
    var len = this.length >>> 0,
    from = Number(arguments[1]) || 0;
    if(from < 0) {
    from += len;
    }
    for(; from < len; from++) {
    if(from in this && this[from] === elt) {
    return from;
    }
    }
    return -1;
    };

    /*
    * Implemented in JavaScript 1.6
    */
    Array.prototype.filter = Array.prototype.filter || function(fun /*, thisp*/) {
    var len = this.length >>> 0;
    if(typeof fun != 'function') { throw new TypeError(fun + ' is not a function'); }
    var res = [], thisp = arguments[1];
    for(var i = 0, val; i < len; i++) {
    if(i in this) {
    val = this[i];
    fun.call(thisp, this[i], i, this) && res.push(val);
    }
    }
    return res;
    };