Array.prototype.forEach.call 给出 TypeError: 非法调用
Array.prototype.forEach.call gives TypeError: Illegal invocation
谁能告诉我为什么这不起作用?
Array.prototype.forEach.call(document.body.children, console.log);
我收到以下错误:
未捕获的类型错误:非法调用(...((匿名功能(
这似乎是无稽之谈,因为以下两者都有效:
Array.prototype.forEach.call(document.body.children, function () {console.log(arguments)});
Array.prototype.forEach.call(document.body.children, l=>console.log(l));
注意:被调用的函数(在本例中
console.log
(只是一个示例,最初的目的是改用document.body.removeChild
,但这以同样的方式失败了。另一个注意事项:我只在Chrome中尝试过这个。我在节点.js控制台中尝试了以下内容,它工作正常:
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
绑定到console
:
Array.prototype.forEach.call(document.body.children, console.log.bind(console));
还有一个绑定运算符的建议:
Array.prototype.forEach.call(document.body.children, ::console.log);
相关文章:
- AJAX调用中的非法调用
- 如何解决这种情况下的非法调用类型错误
- 为什么从数组调用时收到非法调用
- 使用ajax和bootbox进行非法调用
- 未捕获的类型错误:非法调用:模态形式的错误
- 对间谍对象的非法调用
- 非法调用错误 jquery
- $.post投掷”;非法调用”;
- 调用module.exports上的函数时发生CommonJS非法调用错误
- 使用 Web 音频 API 使用 start/noteOn 进行非法调用
- 为什么这会引发未捕获的类型错误:非法调用
- jQuery ajax Uncatch TypeError: 非法调用
- 什么是非法调用类型JavaScript中的错误
- 在 jquery 中将错误作为非法调用
- 为什么某些函数调用在 JavaScript 中被称为“非法调用”
- JavaScript 中的 getUserMedia() 跨浏览器规范化.非法调用
- Array.prototype.forEach.call 给出 TypeError: 非法调用
- 未捕获的类型错误:发送数据时非法调用
- 未捕获的类型错误:从 ajax 发送数据时出现非法调用错误
- 尝试将javascript转换为jquery时出现错误“非法调用”