首页 > 解决方案 > 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 解构赋值,但在这里陷入困境,我无法理解这个函数如何接受参数并设置默认值?

标签: javascriptecmascript-6

解决方案


考虑这个更简单的例子:

function foo({ bar }) {
  console.log(bar);
}

你可以这样称呼它foo({ bar: 42 });并进入42控制台。

但是假设你想要一个默认参数,你想要barand 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

而且因为所有键都是可选的,我们假设空输入等效于空对象,这反过来将使用我们的键的所有默认值。


推荐阅读