(function(fn){
if (!fn.map) fn.map=function(f){var r=[];for(var i=0;i<this.length;i++)r.push(f(this[i]));return r}
if (!fn.filter) fn.filter=function(f){var r=[];for(var i=0;i<this.length;i++)if(f(this[i]))r.push(this[i]);return r}
})(Array.prototype);
Put anywhere before first .map or .filter call. Problem solved. jQuery.map() method doesn't work as expected.
UPDATE:
I've just tested it on sparse arrays: if map or filter argument is a function which accepts and handles undefined
value - it works, but the results are not obvious:
Let's define test sparse array:
var t = []
t[1] = 1; t[3] = 3; t[5] = 5;
Let's see what does IE8 say about t: "[undefined, 1, undefined, 3, undefined, 5]"
Let's try:
t.filter(function(x){return x<4})
What is it, IE8? It's: "[1, 3]". Note - no undefined values. I would personally expect that.
But try THIS:
t.map(function(x){return 2<<x})
And... "[2, 4, 2, 16, 2, 64]". That's weird! :) Try this:
t.map(function(x){return Math.pow(2,x)})
And?... "[NaN, 2, NaN, 8, NaN, 32]" - I would rather expect this result for the previous test. It's at least logical - Math.pow() is supposed to return a number
type, NaN
, regardless of it's meaning IS a special number
type reserved for invalid operations. So the result is more or less correct. It would be fully correct as map
result if t remained a sparse array.
So without further ado - ultimately correct version of map
and filter
methods:
(function(fn){
if (!fn.map) fn.map=function(f){var r=[];for(var i=0;i<this.length;i++)if(this[i]!==undefined)r[i]=f(this[i]);return r}
if (!fn.filter) fn.filter=function(f){var r=[];for(var i=0;i<this.length;i++)if(this[i]!==undefined&&f(this[i]))r[i]=this[i];return r}
})(Array.prototype);
And the test:
var t = []; t[1] = 1; t[3] = 3; t[5] = 5;
var t1 = t.map(function(x){return 2<<x});
var t2 = t.filter(function(x){return x<10});
console.debug(t);
console.debug(t1);
console.debug(t2);
Expected results:
[object Array] [undefined, 1, undefined, 3, undefined, 5]
[object Array][undefined, 4, undefined, 16, undefined, 64]
[object Array][undefined, 1, undefined, 3, undefined, 5]