为什么当作为参数传递给 forEach 时,console.log 不起作用? [英] Why doesn't console.log work when passed as a parameter to forEach?

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

问题描述

这只是出于好奇,但是你们有没有人知道为什么这段代码不起作用?

This is just out of curiosity, but do any of you have an idea why this code won't work?

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

// Prints 'Uncaught TypeError: Illegal invocation' in Chrome

另一方面,这似乎工作正常:

On the other hand, this seems to work fine:

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

所以……?

推荐答案

实际上正如@SLaks 指出的,console.log 似乎在内部使用 this 并且当它作为参数传递时 this 现在指的是数组实例.

Actually as @SLaks pointed out, console.log seems to be using this internally and when it's passed as a parameter this now refers to the array instance.

解决方法很简单:

var c = console.log.bind(console);[1,2,3,4,5].forEach(c);

这篇关于为什么当作为参数传递给 forEach 时,console.log 不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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