【问题标题】:Destructuring and re-structuring in function arguments?函数参数中的解构和重构?
【发布时间】:2018-04-04 07:10:26
【问题描述】:

我正在尝试通过解构来使用命名函数参数和默认值。

function doSomething({arg1 = "foo", arg2 = "bar"} = {}) {
  console.log(arg1, arg2);
}

但我也想访问整个对象,以防用户添加一些额外的字段。这实际上不起作用,但我正在拍摄这样的东西:

function doSomething(parameters = {arg1 = "foo", arg2 = "bar"} = {}) {
  console.log(arg1, arg2, parameters);   
  // parameters should contain arg1 and arg2, plus any additional user supplied keys.
}

有没有使用解构的优雅方法来做到这一点? (我尝试使用arguments[0],但这实际上并不包括我的arg1arg2 的默认值。)

谢谢。

【问题讨论】:

标签: javascript destructuring


【解决方案1】:

你可以这样做:

function doSomething({ arg1 = "foo", arg2 = "bar", ...otherParams } = {}) {
    console.log(arg1, arg2, otherParams);
}

...然后:

doSomething({ anotherParam: 'hello' });

...将记录:

foo bar {anotherParam: "hello"}

这使用了扩展运算符,您可以在最新的 Chrome 中使用它,并在您通过 Babel 转译为 ES5 的生产应用程序中使用它。然而,值得注意的是,这会增加更复杂的转译代码,但并非所有浏览器都原生支持。

另外,从代码可读性和架构的角度来看,这个函数现在在解构、默认参数和扩展运算符方面有很多复杂性,所以我想看看是否有可能简化你正在做的事情以减少需要使用所有这些。

例如,如果你正在构建一个函数来创建一个 DOM 元素,你可以这样写:

function createDOMElement(properties = {}) {
   // Could avoid `const` by doing destructuring in the function signature, but broke it onto another line for better readability.
   const {
    tagName = 'div',
    ...attributes
   } = properties;

   const anElement = document.createElement(tagName);
   Object.keys(attributes).forEach((key) => anElement.setAttribute(key, attributes[key]));
   return anElement;
}

...但是您可以将标签名称作为常规参数而不是命名参数提供并将其简化为:

function createDOMElement(tagName = 'div', attributes = {}) {
   const anElement = document.createElement(tagName);
   Object.keys(attributes).forEach((key) => anElement.setAttribute(key, attributes[key]));
   return anElement;
}

【讨论】:

    【解决方案2】:

    在即将发布的 Javascript 版本中,您可以将剩余参数用于其他属性。

    function doSomething({ arg1 = "foo", arg2 = "bar", ...rest } = {}) {
      console.log(arg1, arg2, rest);
    }
    
    doSomething({ arg1: 'a', arg2: 'b', arg3: 'c' });

    【讨论】:

      【解决方案3】:

      只需创建一个对象,然后将其指定为默认参数:

      const defaultParam = {
        arg1: "foo",
        arg2: "bar"
      };
      
      function doSomething({...parameter}) {
        console.log(parameter);
      }
      
      doSomething({arg3: "Hello"});
      doSomething({...defaultParam, arg1: "New dude!", arg3: "Hello"});

      【讨论】:

      • 我认为这实际上行不通。如果用户在第一个参数中传递任何内容,那么 parameter 将不会以您的默认 arg1arg2 值结束。
      • @user3056556 我明白了,一开始并没有得到你想要的。我更新了我的答案。这应该工作
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-28
      • 2012-11-30
      • 2021-03-10
      • 2019-02-22
      • 1970-01-01
      相关资源
      最近更新 更多