Skip to content

Instantly share code, notes, and snippets.

@calvinmetcalf
Created November 30, 2012 14:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save calvinmetcalf/4175957 to your computer and use it in GitHub Desktop.
Save calvinmetcalf/4175957 to your computer and use it in GitHub Desktop.
iterating

So your most likely going to be iterating through an array or an object, we'll start with an array;

var array = [1,2,3,4,5]; //your array

for(var i = 0; i<array.lengh; i++){
    doStuff(array[i]);
}

the only issue with that is that you are checking the length of the array every time, so instead you could do

for(var i = 0, len = array.length; i<len; i++){
    doStuff(array[i]);
}

note the comma, technically var i = a; var b; var c = whatever; is equivalent to var i = a,b,c = whatever;

lastly modern browsers have new way to modify an array in place like this, the previous two examples are equivalent to

array.forEach(doStuff);

yeah that was easy

now if you wanted the results of it like say the function

function doStuff(v){
v++;
return v;
}
for(var i = 0, len = array.length, out=[]; i<len; i++){
    out.push(doStuff(array[i]));
}

now out = [2, 3, 4, 5, 6];/on modern browsers you can use map so that is equivalent to array.map(doStuff); which btw you can also write an anonymous function

array.map(function(v){return v+1;});

now for objects say you have an object var obj = {a:1,b:2,c:3,d:4,e:5}; there is a shortcut

for(var key in obj){
    console.log(key+": "+obj[key])
}

this is the equivalent of

var keyz = keys(obj);

avoid doing var keys = keys(obj) as that overwrites the function, though keys(object) is actually a shortcut to Object.keys(object);

for(var i = 0, len = keyz.length;i<len;i++){
   console.log(keyz[i]+": "+obj[keyz[i]]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment