Created
February 17, 2016 23:11
-
-
Save johntran/b2fffa4ec55632a741f0 to your computer and use it in GitHub Desktop.
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
//Let's say you have a function that accepts a callback, and applies that call back to each element: | |
forEach(array, callback) { | |
// loop start at 0 index, until it reaches the end of the array, one at a time | |
for(var i=0; i < array.length; i++) { | |
// at the index of that array, have it equal to the result of the callback with "the result of that index of that array" as a parameter | |
array[i] = callback(array[i]) | |
} | |
} | |
example: | |
var arr = [1,2,3] | |
var addOne = function (number) { | |
return number + 1 | |
} | |
var addedOne = forEach(arr, addOne) // returns [2,3,4] | |
/** | |
* Under the hood this is what it looks like | |
* forEach([1,2,3], addOne) { | |
for(var i=0; i < array.length; i++) { | |
array[i] = addOne(array[i]) | |
} | |
} | |
For the first loop: | |
forEach([1,2,3], addOne) { | |
for(var i=0; i < array.length; i++) { | |
array[0] = addOne(array[0]) | |
} | |
} | |
forEach([1,2,3], addOne) { | |
for(var i=0; i < array.length; i++) { | |
array[0] = addOne(1) | |
} | |
} | |
forEach([1,2,3], addOne) { | |
for(var i=0; i < array.length; i++) { | |
array[0] = addOne= function (1) { return 1 + 1 } | |
} | |
} | |
forEach([1,2,3], addOne) { | |
for(var i=0; i < array.length; i++) { | |
array[0] = 2 | |
} | |
} | |
end 1st loop | |
repeat for 2nd loop | |
I hope that helps! text me back if you need clarification. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment