4 ms·
Reducing Map: jQuery vs jQuery vs JavaScript
- intellectronica 16y agoThe post is a bit misleading. The "native" map method is only Javascript 1.6, so it isn't universally available.
- mrspeaker 16y ago"Reducing map: A short look at the similarities between the map functionality of jQuery 1.2+ inline map, jQuery 1.3.2 global map and JavaScipts 1.6+ native map function" didn't fit. But if you're unfortunate enough to have to care about the ol' stuff, there are some nice polyfills on each of the MDC map/reduce/filter/etc pages: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map#Compatibility https://developer.mozilla.org/en/JavaScript/Reference/Global...
- dstein 16y agoYou can make it universally available with: if (!Array.prototype.map) { Array.prototype.map = function(fun /*, thisp */) { "use strict"; if (this === void 0 || this === null) throw new TypeError(); var t = Object(this); var len = t.length >>> 0; 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 t) res[i] = fun.call(thisp, t[i], i, t); } return res; }; }
- Sidnicious 16y agoI'm a big fan of es5-shim (https://github.com/kriskowal/es5-shim/ https://github.com/kriskowal/es5-shim/), which monkey-patches these handy methods in older browsers.
- IgorPartola 16y agoOfftopic follows: One thing that sucks about JS currently is the fact that you have to do Array.prototype.map.call(a, ...) instead of a.map, and even then you don't have a guarantee that the correct function will execute. I know in ECMAScript 5 you can freeze properties of an object, but unless prototypes of basic methods come frozen, it's not ideal.
- brunoc 16y agoWhy exactly do you have to do that? Because some other unknown party could have overwritten the prototype with a new map function? If that's the case, none of the basic objects are safe, not just Array..
- IgorPartola 16y agoRight. My point exactly. In most cases this is not a problem and sometimes can be really nice: like when you want to add some profiling code, etc. However, this is also pretty terrible when it comes to large code bases or when you see libraries out there that modify prototypes of base objects.
- fharper1961 16y agoI had no idea there were 3 different map options available. Are you going to compare performance?
- PanosJee 16y agoI personally use the map functioned defined in Underscore.js
- Swizec 16y agoAlso check out the async library by caolan. Primarily designed for node.js, but also works with client-side. https://github.com/caolan/async https://github.com/caolan/async It's got the nice feature of providing synchronous and asynchronous maps, reduces, filters and everything else you'd expect.