javascript - 如何在 const 函数中获取参数值?
问题描述
下面是我的代码。
我想知道的是,在将参数传递给变量“ok”时,如何在箭头函数“response”中传递返回参数的数据。
const response = (statusCode, formatter = null) => {
const hasFormatter = typeof formatter === 'function';
const format = hasFormatter ? formatter : _ => _;
return (data = null) => {
const response = {
statusCode: statusCode
};
// Why is the data delivered??
if (data) {
response.body = format(data);
}
return response;
}
};
const ok = response(200, JSON.stringify);
// Here, I put the parameter value({foo: 'bar'}) in the variable 'ok'.
console.log( ok({foo: 'bar'}) );
// {statusCode: 200, body: "{"foo":"bar"}"}
解决方案
在评论中你澄清了:
名为响应的函数似乎只有两个参数值。因此,我认为返回参数中名为“data”的参数值不能在“reponse”函数内部的任何地方导入,但事实并非如此。
我看到了你困惑的根源。你不是response
在你得到的时候data
调用,你是在调用它返回的函数。
在这里,您正在调用response
并传递它的两个参数的参数:
const ok = response(200, JSON.stringify);
response
返回一个函数,您在变量ok
. 该函数ok
在调用时使用您传递的参数response
以及它自己的参数data
。(更多关于它如何在这个问题的答案和我贫血的小博客上的一篇过时的帖子response
中使用's 参数。)
所以当你这样做时:
ok({foo: 'bar'})
您正在调用response
返回的函数,并为函数的参数传入一个data
参数。
推荐阅读
- python - PyInstaller 可执行文件无法获取 TorchScript 的源代码
- python - 将 Python 元组列表转换为 R 命名向量
- .net - 使用 Azure AD 管理 SQL 会话状态
- javascript - 如果下一个元素等于前一个元素,如何减少JS数组长度
- python - 了解访问字典 Python 中的键和值
- python - Pandas 读取 CSV 缺失行
- spyne - Python - Spyne RPC 工具包有什么招摇的吗?
- azure-devops - 如何在 Azure DevOps 中删除不需要的工件
- javascript - 使用标准 Javascript 的 Deck.gl HexagonLayer 工具提示
- javascript - SyntaxError:使用 Firebase 时出现意外的标识符