Javascript中不写参数调用方法的捷径 [英] Shortcut of calling a method without writing parameters in Javascript

查看:20
本文介绍了Javascript中不写参数调用方法的捷径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我需要澄清的代码.我期待这段代码可以像 Option 2 一样一个一个地控制 'mango', 'apple', 'orange' 但这会抛出另一个我没有得到的输入JavaScript 如何吐出这个输出.

Following is the code in which I need some clarification. I was expecting this code to console 'mango', 'apple', 'orange' one by one similar to Option 2 but this is throwing another input which I am not getting how JavaScript is spitting this output.

const myFunc = (...data) => (data.map(console.log))

myFunc('mango', 'apple', 'orange')

选项 2 -(预期输出)

var myFunc = (...data) => {
  data.map(x => {
    console.log(x)
  })
}

myFunc('mango', 'apple', 'orange')

请纠正我的理解,因为我认为 data.map(console.log) 只会记录项目.

Correct my understanding with this please, as I was thinking that data.map(console.log) will log the items only.

推荐答案

您的代码运行良好,应该为其他函数产生预期的结果.

Array#map 接受一个回调函数,它将为数组的每个元素调用.MDN:

Your code works fine, and should produce the expected result for other functions.

Array#map accepts a callback function, which it will call for each element of the array. MDN:

回调函数接受以下参数:

The callback function accepts the following arguments:

currentValue
数组中正在处理的当前元素.

currentValue
The current element being processed in the array.

indexOptional
数组中正在处理的当前元素的索引.

indexOptional
The index of the current element being processed in the array.

arrayOptional
调用了数组映射.

arrayOptional
The array map was called upon.

因为您将 console.log 作为回调函数传递,所以您可以有效地编写:

Because you're passing console.log as the callback function, you're effectively writing this:

const myFunc = (...data) => (data.map((curVal,index,arr) => console.log(curVal,index,arr)))

myFunc('mango', 'apple', 'orange')

所以额外的输出是因为您还在不知不觉中记录了 indexarray 参数.

So the extra output is because you're also logging the index and array parameters unknowingly.

请注意,您使用的任何其他函数也会收到这些额外的参数.如果他们只接受一个参数,那么它应该完全按照您的预期工作.

Just be aware that any other function you use will also receive these extra parameters. If they only accept one parameter, then it should work exactly as you expect.

这篇关于Javascript中不写参数调用方法的捷径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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