use*_*556 6 javascript destructuring
我正在尝试使用destructuring来使用命名函数参数和默认值.
function doSomething({arg1 = "foo", arg2 = "bar"} = {}) {
console.log(arg1, arg2);
}
Run Code Online (Sandbox Code Playgroud)
但我也想访问整个对象,以防用户添加一些额外的字段.这实际上不起作用,但我正在拍摄这样的事情:
function doSomething(parameters = {arg1 = "foo", arg2 = "bar"} = {}) {
console.log(arg1, arg2, parameters);
// parameters should contain arg1 and arg2, plus any additional user supplied keys.
}
Run Code Online (Sandbox Code Playgroud)
有没有一种优雅的方法来使用解构来做到这一点?(我尝试过使用arguments[0]但实际上并没有包含我的默认值arg1,和arg2.)
谢谢.
你可以这样做:
function doSomething({ arg1 = "foo", arg2 = "bar", ...otherParams } = {}) {
console.log(arg1, arg2, otherParams);
}
Run Code Online (Sandbox Code Playgroud)
...进而:
doSomething({ anotherParam: 'hello' });
Run Code Online (Sandbox Code Playgroud)
...会记录:
foo bar {anotherParam: "hello"}
Run Code Online (Sandbox Code Playgroud)
这使用了扩展运算符,您可以在最新的 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;
}
Run Code Online (Sandbox Code Playgroud)
...但是您可以只提供标签名称作为常规参数而不是命名参数,并将其简化为:
function createDOMElement(tagName = 'div', attributes = {}) {
const anElement = document.createElement(tagName);
Object.keys(attributes).forEach((key) => anElement.setAttribute(key, attributes[key]));
return anElement;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
220 次 |
| 最近记录: |