为什么非法调用console.log作为函数参数? [英] Why is console.log illegaly invocated as a function parameter?

查看:110
本文介绍了为什么非法调用console.log作为函数参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试时

  [1,2,3] .forEach(alert); 

它会按照预期为数组中的每一项打开消息框。



但是,当我尝试

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

我收到以下错误

  Uncaught TypeError:非法调用

为什么?

解决方案

我个人得到无效的调用对象



请参阅 [1,2,3] .forEach(console.log)本质上是对数组进行迭代的简写方式,对于运行 console.log.call(theArray,theItem)的每个项目。然而, console.log 要求这个是一个类型为 Console $ b

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


When I try

[1,2,3].forEach(alert);

it opens message box for every item of the array as expected.

But when I try

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

I receive following error

Uncaught TypeError: Illegal invocation

Why?

解决方案

Personally I get Invalid calling object.

See, [1,2,3].forEach(console.log) is essentially a shorthand way of iterating over the array and for each item running console.log.call(theArray,theItem). However, console.log requires that this be an object of type Console, thus the error.

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

这篇关于为什么非法调用console.log作为函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆