Created
January 17, 2011 17:59
-
-
Save premasagar/783165 to your computer and use it in GitHub Desktop.
Enumerable arrays and objects - useful methods
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
var forEach = Array.prototype.forEach ? | |
function(array, fn, thisp){ | |
return array.forEach(fn, thisp); | |
} : | |
function(array, fn, thisp){ | |
var i = 0, | |
arrayCopy = Object(array), | |
length = arrayCopy.length; | |
for (; i < length; i++){ | |
if (i in arrayCopy){ | |
fn.call(thisp, arrayCopy[i], i, arrayCopy); | |
} | |
} | |
return arrayCopy; | |
}; | |
var arrayMap = Array.prototype.map ? | |
function(array, fn, thisp){ | |
return array.map(fn, thisp); | |
} : | |
function(array, fn, thisp){ | |
var i = 0, | |
arrayCopy = Object(array), | |
length = arrayCopy.length, | |
result = new Array(length); | |
for (; i < length; i++){ | |
if (i in arrayCopy) { | |
result[i] = fn.call(thisp, arrayCopy[i], i, arrayCopy); | |
} | |
} | |
return result; | |
}; | |
function map(obj, fn){ | |
var result = [], | |
prop, val; | |
for (prop in obj){ | |
if (obj.hasOwnProperty(prop)){ | |
val = fn.call(obj, prop, obj[prop]); | |
result.push(val); | |
} | |
} | |
return result; | |
} | |
var objectKeys = Object.keys ? | |
Object.keys : | |
function(obj){ | |
var keys = [], | |
key; | |
for (key in obj){ | |
if (obj.hasOwnProperty(key)){ | |
keys.push(key); | |
} | |
} | |
return keys; | |
}; | |
/* // or replace loop: | |
jQuery.each(obj, function(key){ | |
keys.push(key); | |
}); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment