javascript - What is the correct way to use object destructing in this situation?
问题描述
I recently added ESLint to a project to improve the project and my skills.
const server = app.listen(config.port, () => {
const host = server.address().address;
const port = server.address().port;
log.info(`API server listening on host ${host}, port ${port}`);
});
ESLint says to use destructuring for line 2 and 3.
The 'quick fix' that VSCode gives me is
const server = app.listen(config.port, () => {
const { host } = server.address();
const { port } = server.address();
log.info(`API server listening on host ${host}, port ${port}`);
});
This feels... wrong somehow.
If the quick fix isn't actually the correct fix, can someone educate on the proper way to use destructuring here.
If this is indeed the correct fix, can someone explain reasons this is better than it was before.
I don't want to blindly follow ESLint but I'm not about to ignore the advice of a tool like ESLint either. Like I said, I want to learn.
解决方案
您可以在将字段映射到不同名称的同时破坏该值。
const mockServer = {
address() {
return {
address: 'foo',
port: 3000,
};
},
};
const { address: host, port } = mockServer.address();
console.log(host, port);
推荐阅读
- inno-setup - 如何让 Inno Setup 解压缩文件(全部作为一个安装过程的一部分)
- java - Liferay DXP 7.2 监听器启动失败(干净版)
- nlp - HuggingFace GPT2DoubleHeadsModel 可以用于非多选下一个令牌预测吗?
- angular - 在我的 Angular 服务中使用 Promise 而不是 Observables
- css - 除非我使用内联样式,否则不会应用 CSS 高度
- oauth-2.0 - Stackdriver 登录重定向循环
- javascript - 签名板压印文本大小在画布比例内变化
- mongodb - 如何计算猫鼬的平均值?
- xcode - Xcode 在物理设备上运行应用程序失败
- java - 如何在spring jpa中组合4个表(查询)