Javascript Array.prototype.forEach.call给出TypeError:非法调用
有人能告诉我为什么这不起作用吗Javascript Array.prototype.forEach.call给出TypeError:非法调用,javascript,arrays,foreach,call,typeerror,Javascript,Arrays,Foreach,Call,Typeerror,有人能告诉我为什么这不起作用吗 Array.prototype.forEach.call(document.body.children,console.log) 我得到以下错误: 未捕获类型错误:非法调用(…)(匿名函数) 这似乎是胡说八道,因为以下两种方法都有效: Array.prototype.forEach.call(document.body.children,函数(){console.log(arguments)}); call(document.body.children,l=>co
Array.prototype.forEach.call(document.body.children,console.log)代码>
我得到以下错误:
未捕获类型错误:非法调用(…)(匿名函数)
这似乎是胡说八道,因为以下两种方法都有效:
Array.prototype.forEach.call(document.body.children,函数(){console.log(arguments)});
call(document.body.children,l=>console.log(l));
注意:正在调用的函数(console.log
,在本例中)只是一个示例,最初的目的是使用document.body.removeChild
,但同样失败
另一个注意事项:我只在Chrome中尝试过。我在node.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
,确定此
值来进行修复:
Array.prototype.forEach.call(document.body.children, console.log, console);
或者您可以将console.log
绑定到console
:
Array.prototype.forEach.call(document.body.children, console.log.bind(console));
还有一项建议是:
这是因为必须对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
,确定此
值来进行修复:
Array.prototype.forEach.call(document.body.children, console.log, console);
或者您可以将console.log
绑定到console
:
Array.prototype.forEach.call(document.body.children, console.log.bind(console));
还有一项建议是:
console.log.bind(console)
,document.body.removeChild.bind(document.body)
Ah所以我需要绑定document.body
(或DOM元素)我正在调用removeChild
on-谢谢@SergeSeredenkoconsole.log.bind(console)
,document.body.removeChild.bind(document.body)
Ah所以我需要绑定document.body
(或DOM元素),我正在调用上的removeChild
-谢谢@SergeSeredenko