【问题标题】:unclear on ES6 destructuring function parameter defaults [duplicate]不清楚 ES6 解构函数参数默认值 [重复]
【发布时间】:2017-05-17 14:23:21
【问题描述】:

所以在 MDN 文档中解构函数默认值它给出了下面的例子。

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
});

但是我可以在第一行作为function drawES2015Chart({size = 'big', cords = {x: 0, y: 0}, radius = 25}) 运行这个示例

所以省略了={} 部分。我不确定这为什么有效,如果较短的形式实际上同样正确,那么使用较长的形式会有什么好处。

【问题讨论】:

  • 当你在你的版本中传入nil/undefined/nothing 会发生什么? (例如,没有 = {} 默认值。)
  • @DaveNewton 在传递null 时仍然会出现异常,因为它不会触发默认值替换

标签: javascript ecmascript-6 destructuring


【解决方案1】:

按照您的建议重构函数:

function drawES2015Chart({size = 'big', cords = {x: 0, y: 0}, radius = 25}) {
    console.log(size, cords, radius);
}

尝试不带参数调用它时会导致错误:

drawES2015Chart(); // throws TypeError

不过,你可以这样称呼它:

drawES2015Chart({});

所以,= {} 最后所做的是让您能够调用

drawES2015Chart();

默认为

drawES2015Chart({});

默认为

drawES2015Chart({size = 'big', cords = {x: 0, y: 0}, radius = 25});

【讨论】:

    【解决方案2】:

    最后的= {}默认整个参数对象,以确保如果有人在没有任何参数的情况下调用您的函数(drawES2015Chart({}) vs drawES2015Chart()),您不会尝试解构undefined

    如果你没有这个守卫:

    function foo({x = 10}) {
      return x;
    }
    
    foo(); // TypeError: can't convert undefined to object
    foo({}); // 10
    

    【讨论】:

      【解决方案3】:

      尝试删除= {}并执行drawES2015Chart();

      它可以防止 undefined 被解构。

      【讨论】:

        猜你喜欢
        • 2016-10-30
        • 2017-04-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-14
        • 1970-01-01
        • 1970-01-01
        • 2017-07-12
        • 1970-01-01
        相关资源
        最近更新 更多