简体   繁体   中英

Functional Programming: Printing to JS console in Chrome

I'm implementing functional programming from Eloquent Javascript to my JS console in Google Chrome. There's a function that loops through each element in an array and performs the given action in the initial parameter to said element.

function forEach(array, action) {
    for (var i = 0; i < array.length; i++)
       action(array[i]);
}   

forEach(["Wampeter", "Foma", "Granfalloon"], console.log);

I am expecting the console to print out each item in my array, but I get this in red:

TypeError: 'Illegal Invocation'  

Is there a way I can print this on my js console or should I use something else to compile the code?

When you pass it to forEach , the function is losing the reference to its this value (the console object). The following should work:

function forEach(array, action) {
    for (var i = 0; i < array.length; i++)
       action(array[i]);
}   

forEach(["Wampeter", "Foma", "Granfalloon"], console.log.bind(console));

http://jsfiddle.net/th2A5/

For browsers that don't support bind , you can use the shim available on the MDN documentation page

This should work for you...

function forEach(array, action) {
    for (var i = 0; i < array.length; i++)
       action(array[i]);
}   

forEach(["Wampeter", "Foma", "Granfalloon"], function(x) {console.log(x);});

For some reason Chrome's console.log doesn't seem to work as a callback.

This code seems to work, though: for (item in ["a","b","c"]) console.log(item); and a = ["a","b","c"]; for (i = 0; i < a.length; i++) console.log(a[i]); a = ["a","b","c"]; for (i = 0; i < a.length; i++) console.log(a[i]);

I'd not suggest using the JS console anyway, but that's up to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM