javascript - Array.prototype.forEach.call 给出 TypeError : Illegal invocation

标签 javascript arrays foreach call typeerror

谁能告诉我为什么这不起作用?

Array.prototype.forEach.call(document.body.children, console.log);

我收到以下错误:

Uncaught TypeError: Illegal invocation(…)(anonymous function)

这似乎是无稽之谈,因为以下两者都有效:

Array.prototype.forEach.call(document.body.children, function () {console.log(arguments)});
Array.prototype.forEach.call(document.body.children, l=>console.log(l));

NOTE: the function being called (console.log in this case) is just an example, the original intent was to use document.body.removeChild instead, but this failed in the same way.

ANOTHER NOTE: I've only tried this in Chrome. I tried the following in a node.js console and it worked fine:

Array.prototype.forEach.call(myArray, console.log)

最佳答案

这是因为必须在 console 对象上调用 console.log 方法:

var log = console.log;
log(123); /* TypeError: 'log' called on an object that
             does not implement interface Console. */
log.call(console, 123); /* Works */

您可以通过将第三个参数传递给 forEach 来修复,该参数确定 this 值:

Array.prototype.forEach.call(document.body.children, console.log, console);

或者您可以将 console.log 绑定(bind)到 console:

Array.prototype.forEach.call(document.body.children, console.log.bind(console));

还有一个bind operator的提案:

Array.prototype.forEach.call(document.body.children, ::console.log);

关于javascript - Array.prototype.forEach.call 给出 TypeError : Illegal invocation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35416462/

相关文章:

javascript - 无需超出页面即可更新数据库

javascript - 一段时间后如何更改组件的类?

python - 将大型 numpy 数组拆分为训练和测试的内存有效方法

php - 使用 XML 提取 XML 中的 ECB 汇率时遇到一些问题..有问题的完整源代码

php - 如何在 php 中为每个循环调用多个表

javascript - Ruby on Rails 3.1 : error with "render" in javascrtip (AJAX) from RailsCasts (Search, 使用 AJAX 排序、分页)

javascript - html 中 nodeJS child_process 的样式输出

arrays - 如何将字符串转换为结构的复杂数组并在 hive 中 explode

java - 如何将整数堆栈转换/转换为 double 组?

java - 为什么我在此示例中没有收到 java.util.ConcurrentModificationException?