javascript - Functional Programming: Printing to JS console in Chrome -


i'm implementing functional programming eloquent javascript js console in google chrome. there's function loops through each element in array , performs given action in initial parameter said element.

function foreach(array, action) {     (var = 0; < array.length; i++)        action(array[i]); }     foreach(["wampeter", "foma", "granfalloon"], console.log); 

i expecting console print out each item in array, in red:

typeerror: 'illegal invocation'   

is there way can print on js console or should use else compile code?

when pass foreach, function losing reference this value (the console object). following should work:

function foreach(array, action) {     (var = 0; < array.length; i++)        action(array[i]); }     foreach(["wampeter", "foma", "granfalloon"], console.log.bind(console)); 

http://jsfiddle.net/th2a5/

for browsers don't support bind, can use shim available on mdn documentation page


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -