Skip to content

Instantly share code, notes, and snippets.

@yangg
Created September 7, 2012 02:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yangg/3662658 to your computer and use it in GitHub Desktop.
Save yangg/3662658 to your computer and use it in GitHub Desktop.
JavaScript implements
// 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;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment