我想逐行打印数组并换行。简单实现方法是使用
现在,如果我使用ES6箭头函数的语法糖,
[1,2,3].forEach(function(x) {console.log(x)})
,以此作为输出结果。1
2
3
现在,如果我使用ES6箭头函数的语法糖,
michel$ node
> [1,2,3].forEach(x => console.log(x))
1
2
3
undefined
>
> [1,2,3].forEach(console.log)
1 0 [ 1, 2, 3 ]
2 1 [ 1, 2, 3 ]
3 2 [ 1, 2, 3 ]
undefined
在 forEach
回调函数中省略函数参数时,第二个版本看起来返回了自身的笛卡尔积。
在其他函数式编程语言(如Scala)中,这是完全可以的,为什么在JavaScript中会被认为是“错误”的呢?
michel$ scala
scala> Array(1,2,3).foreach(x => println(x))
1
2
3
scala> Array(1,2,3).foreach(println)
1
2
3
console.log(console.log)
,你会得到答案。 - Durga