这只是出于好奇,但你们中有人知道为什么这段代码不起作用吗?
[1, 2, 3, 4, 5].forEach(console.log);
// Prints 'Uncaught TypeError: Illegal invocation' in Chrome
另一方面,这似乎工作正常:
[1, 2, 3, 4, 5].forEach(function(n) { console.log(n) });
所以... ?
最佳答案
值得指出的是,console.log
的实现在行为上存在差异。 .在节点 v0.10.19 下,您不会收到错误消息;你只是看到这个:
> [1,2,3,4,5].forEach(console.log);
1 0 [ 1, 2, 3, 4, 5 ]
2 1 [ 1, 2, 3, 4, 5 ]
3 2 [ 1, 2, 3, 4, 5 ]
4 3 [ 1, 2, 3, 4, 5 ]
5 4 [ 1, 2, 3, 4, 5 ]
这是因为回调到
forEach
是一个三参数函数,取值、索引和数组本身。函数console.log
看到这三个参数并尽职尽责地记录它们。但是,在 Chrome 浏览器控制台下,您会得到
> [1,2,3,4,5].forEach(console.log);
TypeError: Illegal invocation
在这种情况下,
bind
将工作: > [1,2,3,4,5].forEach(console.log.bind(console));
1 0 [ 1, 2, 3, 4, 5 ]
2 1 [ 1, 2, 3, 4, 5 ]
3 2 [ 1, 2, 3, 4, 5 ]
4 3 [ 1, 2, 3, 4, 5 ]
5 4 [ 1, 2, 3, 4, 5 ]
但还有另一种方法:注意
forEach
的第二个参数取值 this
在回调中使用:> [1,2,3,4,5].forEach(console.log, console)
1 0 [ 1, 2, 3, 4, 5 ]
2 1 [ 1, 2, 3, 4, 5 ]
3 2 [ 1, 2, 3, 4, 5 ]
4 3 [ 1, 2, 3, 4, 5 ]
5 4 [ 1, 2, 3, 4, 5 ]
它适用于我的 Chrome 控制台和节点。当然,我确定您想要的只是值(value)观,所以恐怕最好的解决方案确实是:
> [1,2,3,4,5].forEach(function (e) {console.log(e)});
1
2
3
4
5
节点的行为是否是一个错误,或者它只是利用了
console.log
的事实。不是由 ECMA 指定的,这本身就很有趣。但是不同的行为,以及你必须知道你的回调是否使用 this
的事实。很重要,这意味着我们必须退回到直接编码,即使由于关键字 function
很冗长。 .
关于javascript - 为什么console.log 在作为参数传递给forEach 时不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9639167/