javascript - ES6 破坏赋值
问题描述
function drawES2015Chart({size = 'big',cords = {x: 0,y: 0},radius = 25} = {}) {
console.log(size, cords, radius);
// do some chart drawing
}
drawES2015Chart({
cords: {x: 18, y: 30},
radius: 30
});
我在 Mozilla 的开发人员网站的Destructuring assignment下找到了这个片段。
我正在学习 ES6 解构赋值,但在这里陷入困境,我无法理解这个函数如何接受参数并设置默认值?
解决方案
考虑这个更简单的例子:
function foo({ bar }) {
console.log(bar);
}
你可以这样称呼它foo({ bar: 42 });
并进入42
控制台。
但是假设你想要一个默认参数,你想要bar
and baz
,但是设为baz
可选,默认值为true
,你可以这样做:
function foo({ bar, baz = true }) {
console.log(bar, baz);
}
调用那个foo({ bar: 42 })
会导致42, true
.
现在假设我们希望所有参数都是可选的:
function foo({ bar = 42, baz = true }) {
console.log(bar, baz);
}
foo({}); // 42, true
// however
foo(); // TypeError: Cannot destructure property `bar` of 'undefined' or 'null'.
糟糕,您无法解构未传递的值。因此,您也需要该参数具有默认值:
function foo({ bar = 42, baz = true } = {}) {
console.log(bar, baz);
}
foo(); // 42, true. Yey!
因此,对于您的具体示例:
function drawES2015Chart({size = 'big', cords = {x: 0, y: 0}, radius = 25} = {}) {
...
}
接受一个可选参数,一个具有三个可选键的对象:
size
是一个可选键,默认值为big
cords
是一个可选键,默认值为{x: 0, y: 0}
radius
是一个可选键,默认值为25
而且因为所有键都是可选的,我们假设空输入等效于空对象,这反过来将使用我们的键的所有默认值。
推荐阅读
- node.js - 在节点 js 中合并文件?
- r - 从一列序列中选择特定序列,中间有最大距离
- c# - 使用 Plugin.FileUploader 上传图像时 iOS 13+ 中的“路径共享冲突”错误
- python - Python将列拆分为最小值和最大值
- javascript - 是否可以将 blob 转换为 pptx?
- docker - 在自定义 GitHub 操作中挂载运行 docker-in-docker 容器的文件夹
- .net - 即使工作正常,Visio VSTO 中的 .NET OpenFileDialog FileNotFoundException
- server - 有没有办法在发布之前以服务器模式查看 Tableau 仪表板/工作表?
- php - API POST 请求返回 HTML 而不是 JSON 并且没有进入我的 HTML 元素
- c# - IOCPT/IOCP - 它只存在于 Windows 中吗?