Nes*_*esh 1 html javascript loops ecmascript-6 reactjs
以下是我需要澄清的代码。我希望这段代码能够'mango', 'apple', 'orange'
像选项 2 一样一一进行控制台,但这会抛出另一个输入,我不知道 JavaScript 是如何吐出这个输出的。
const myFunc = (...data) => (data.map(console.log))
myFunc('mango', 'apple', 'orange')
Run Code Online (Sandbox Code Playgroud)
选项 2 -(预期产出)
var myFunc = (...data) => {
data.map(x => {
console.log(x)
})
}
myFunc('mango', 'apple', 'orange')
Run Code Online (Sandbox Code Playgroud)
请纠正我的理解,因为我认为data.map(console.log)
只会记录项目。
Array#map
接受一个回调函数,它将为数组的每个元素调用。MDN:
回调函数接受以下参数:
currentValue
数组中正在处理的当前元素。
indexOptional
数组中正在处理的当前元素的索引。
arrayOptional
调用了数组映射。
因为您是console.log
作为回调函数传递的,所以您可以有效地编写以下代码:
const myFunc = (...data) => (data.map((curVal,index,arr) => console.log(curVal,index,arr)))
myFunc('mango', 'apple', 'orange')
Run Code Online (Sandbox Code Playgroud)
所以额外的输出是因为你也在不知不觉中记录了index
和array
参数。
请注意,您使用的任何其他函数也会收到这些额外的参数。如果他们只接受一个参数,那么它应该完全按照您的预期工作。
归档时间: |
|
查看次数: |
211 次 |
最近记录: |