Created
August 5, 2012 16:35
-
-
Save jaredwilli/3265812 to your computer and use it in GitHub Desktop.
forEach in javascript the right way
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| forEach, version 1.0 | |
| Copyright 2006, Dean Edwards | |
| License: http://www.opensource.org/licenses/mit-license.php | |
| */ | |
| // array-like enumeration | |
| if (!Array.forEach) { // mozilla already supports this | |
| Array.forEach = function(array, block, context) { | |
| for (var i = 0; i < array.length; i++) { | |
| block.call(context, array[i], i, array); | |
| } | |
| }; | |
| } | |
| // generic enumeration | |
| Function.prototype.forEach = function(object, block, context) { | |
| for (var key in object) { | |
| if (typeof this.prototype[key] == "undefined") { | |
| block.call(context, object[key], key, object); | |
| } | |
| } | |
| }; | |
| // character enumeration | |
| String.forEach = function(string, block, context) { | |
| Array.forEach(string.split(""), function(chr, index) { | |
| block.call(context, chr, index, string); | |
| }); | |
| }; | |
| // globally resolve forEach enumeration | |
| var forEach = function(object, block, context) { | |
| if (object) { | |
| var resolve = Object; // default | |
| if (object instanceof Function) { | |
| // functions have a "length" property | |
| resolve = Function; | |
| } else if (object.forEach instanceof Function) { | |
| // the object implements a custom forEach method so use that | |
| object.forEach(block, context); | |
| return; | |
| } else if (typeof object == "string") { | |
| // the object is a string | |
| resolve = String; | |
| } else if (typeof object.length == "number") { | |
| // the object is array-like | |
| resolve = Array; | |
| } | |
| resolve.forEach(object, block, context); | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment