var arr = [1,2,3,4,5,6,7] var map = []; var subarray = []; for (var i = 0, len = arr.length; i <len; i ++) { var item = arr [i]; // do something alert (item); // map and sub if (/ * some condition * /) { map.push (item +1); subarray.push (item) } }
var arr = [1,2,3,4,5,6,7] arr.forEach (function ((element, index, array) {alert (element);}) var map = arr.map (function ((element, index, array) { if (/ * some condition * /) return element; }) var subarray = arr.filter (function ((element, index, array) {return / * some condition * /})
var writer = { sb: [], write: function (s) { this.sb.push (s); }, writeln: function (s) { this.write (s + "\ n"); }, toString: function () { return this.sb.join (""); } }; [2, 5, 9] .forEach (writer.writeln, writer); print (writer.toString ()); // assumes print is already defined
if (! Array.prototype.forEach) { Array.prototype.forEach = function (fun / *, thisp * /) { var len = this.length; if (typeof fun! = "function") throw new TypeError (); var thisp = arguments [1]; for (var i = 0; i <len; i ++) { if (i in this) fun.call (thisp, this [i], i, this); } }; } if (! Array.prototype.filter) { Array.prototype.filter = function (fun / *, thisp * /) { var len = this.length; if (typeof fun! = "function") throw new TypeError (); var res = new Array (); var thisp = arguments [1]; for (var i = 0; i <len; i ++) { if (i in this) { var val = this [i]; // in case fun mutates this if (fun.call (thisp, val, i, this)) res.push (val); } } return res; }; } if (! Array.prototype.map) { Array.prototype.map = function (fun / *, thisp * /) { var len = this.length; if (typeof fun! = "function") throw new TypeError (); var res = new Array (len); var thisp = arguments [1]; for (var i = 0; i <len; i ++) { if (i in this) res [i] = fun.call (thisp, this [i], i, this); } return res; }; }
Source: https://habr.com/ru/post/24857/
All Articles