This question already has an answer here:
TypeError: Illegal Invocation on console.log.apply
                                
                                    (1个答案)
                                
                        
                                3年前关闭。
            
                    
为什么下面的代码不起作用?它正在非法调用异常中:

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

最佳答案

您需要这样做:

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


您可以将上述内容称为:

forEach([1,2,3], function(value){
    console.log(value)
});


要么

forEach([1,2,3], console.log.bind(console));

关于javascript - javascript函数作为参数-非法调用。为什么? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38685278/

10-13 06:47