你可以这样做:
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;
}