我正在尝试通过解构来使用命名函数参数和默认值。
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]
,但这实际上并不包括我的 arg1
和 arg2
的默认值。)
谢谢。
最佳答案
你可以这样做:
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/