4

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?

4

3 回答 3

2

当您将它传递给 时forEach,该函数将失去对其this值(console对象)的引用。以下应该有效:

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/

对于不支持的浏览器bind,您可以使用MDN 文档页面上提供的 shim

于 2013-04-17T22:59:45.583 回答
1

这应该对你有用......

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

forEach(["Wampeter", "Foma", "Granfalloon"], function(x) {console.log(x);});
于 2013-04-17T22:53:56.693 回答
0

由于某种原因,Chrome 的 console.log 似乎不能作为回调。

不过,这段代码似乎有效:for (item in ["a","b","c"]) console.log(item);a = ["a","b","c"]; for (i = 0; i < a.length; i++) console.log(a[i]);

无论如何,我不建议使用 JS 控制台,但这取决于你。

于 2013-04-17T22:55:46.980 回答