Here you can find the source of forEach(callback, thisArg)
/**/*w ww. j a v a 2 s . co m*/ * Array foreach() * * @Reference: * http://stackoverflow.com/questions/23614054/javascript-nuances-of-myarray-foreach-vs-for-loop * http://javascriptplayground.com/blog/2012/06/writing-javascript-polyfill/ * http://www.2ality.com/2011/04/iterating-over-arrays-and-objects-in.html * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach * */ // Polyfill for forEach() Array.prototype.forEach = function (callback, thisArg) { if (typeof callback !== 'function') { throw new TypeError(callback + ' is not a function.'); } var len = this.length; // Array length for (var i = 0; i < len; i++) { callback.call(thisArg, this[i], i, this); } }; // Example of forEach() function logArrayElements(currElement, currIndex, originalArray) { console.log('a[' + currIndex + '] = ' + currElement); } // Note there is no member at 2 so it isn't visited [2, 5, , 9].forEach(logArrayElements); // logs: // a[0] = 2 // a[1] = 5 // a[3] = 9
Array.prototype.forEach = function(callback){ let arr = this; for (var i = 0; i < arr.length; i++) { callback(arr[i], i, arr);
Array.prototype.forEach = function(callback){ var a = 0, len = this.length; while(a < len){ callback(this[a], a++, this); };
Array.prototype.forEach = Array.prototype.forEach || function (callback) { var self = this; for (var i = 0; i < self.length; i++) { var item = self[i]; callback(item, i, self);
Array.prototype.forEach = Array.prototype.forEach || function (callback, context) { context = context || window; var l = this.length; for (var i = 0; i < l; i++) callback.call(context, this[i], i, this); };
Array.prototype.forEach = function (callback, context) { for (var index in this) { var item = this[index]; if (!callback(index, item, context)) { break; };
Array.prototype.forEach = function(cb){ for(var k in this) cb(this[k]); };
Array.prototype.forEach = function(cb) { for (var i = 0; i < this.length; i++) { cb(this[i]); };
'use strict'; Array.prototype.forEach = function(cb) { for(let i = 0 ; i < this.length ; i++) { cb(this[i]); };
Array.prototype.forEach = function(fn) { for (var i = 0; i < this.length; i++) fn(this[i]);