Skip to content

Instantly share code, notes, and snippets.

@colynb
Created August 7, 2012 22:48
Show Gist options
  • Save colynb/3290235 to your computer and use it in GitHub Desktop.
Save colynb/3290235 to your computer and use it in GitHub Desktop.
Array prototypes
/*
* Foreach
* Example:
* var arr = [1,2,3,4];
* arr.foreach(function(i,item) {
* console.log(i, item);
* });
*
*/
Array.prototype.foreach = function(action) {
for (var i = 0; i < this.length; i++) {
action(i, this[i]);
}
};
/*
* Sum (uses 'foreach' prototype)
* Example:
* var arr = [1,2,3,4];
* console.log(arr.sum());
*
*/
Array.prototype.sum = function() {
var t = 0;
this.foreach(function(i,item) {
t += parseInt(item,10);
});
return t;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment