javascript - 函数参数中的解构和重构?

标签 javascript destructuring

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

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 的默认值。)

谢谢。

最佳答案

你可以这样做:

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

...然后:

doSomething({ anotherParam: 'hello' });

...将记录:

foo bar {anotherParam: "hello"}

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

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

例如,如果您要构建一个函数来创建 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;
}

关于javascript - 函数参数中的解构和重构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49644881/

相关文章:

javascript - 从字符串中删除多个字符系列

Groovy 在列表上的不一致解构/分解?

javascript - 如何保护代码免于解构 Javascript 中的空值?

javascript - 解构一个对象并创建带有键名的变量 Javascript

javascript - 是否有多次分配 window[functionName] = functionName 的简写?

javascript - 对多个 View 使用 angular-tour 会产生意想不到的结果

javascript - 将 DateTimePicker 传递给值并从值读取的简单方法是什么?

javascript - 被推送到数组的缓存选择器

javascript - 什么是AJAX,它如何工作?

javascript - 将 Array(destructured) 添加到 Set 中的功能方法是什么