Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Each
function(
a, // array/object to be parsed
f // function called on each elements
){
for(var i in a){ // iterating all property of obj/array
if(hasOwnProperty.call(a,i)) // check if is no inherited property
f(a[i], i); // call function with property & iteration
}
}
function(a,f){for(var i in a){if(hasOwnProperty.call(a,i))f(a[i], i)}}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 JEREMY BARBE http://www.shwaark.com
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "each",
"description": "Small each implementation",
"keywords": [
"each",
"iteration",
"parse"
]
}
<!DOCTYPE html>
<title>Foo</title>
<h1>Array</h1>
<div>Expected value: <b> 1 2 3 4</b></div>
<div>Actual value: <b id="ret1"></b></div>
<h1>Obj</h1>
<div>Expected value: <b> 1 : something 3 : 3 oops : function (){}</b></div>
<div>Actual value: <b id="ret2"></b></div>
<script>
var each = function(a,f){for(var i in a){if(hasOwnProperty.call(a,i))f(a[i], i)}}
var array = [1,2,3,4];
var obj = {1: 'something','oops': function(){}, 3:3};
each(array, function(elem, i){
document.getElementById("ret1").innerText += " "+elem;
})
each(obj, function(elem, i){
document.getElementById("ret2").innerText += " "+i+" : "+elem.toString();
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment