javascript - 符合 ES6 标准的 JavaScript 代码优化
问题描述
我对 ES6 不是很擅长,因此期待得到一只小手 :c。如何优化此代码以获得更好的视觉外观?我尝试了以下解决方案,但是,我确信我可以在这里使用类似或类似的数组Array.prototype
方法。.map()
这里的想法是确保 const 列表永远不会出现undefined
,如果它们是 - 使用右侧的情况:
function getLeadingComments(context) {
const contextOptions = context?.options[0];
const description = contextOptions?.description || 'React based Progressive Web App';
const author = contextOptions?.author || '';
const license = contextOptions?.license || 'OSL-3.0';
const packageName = contextOptions?.package || 'Powered by My Project';
return `/**
* ${description}
*
* Copyright © ${author}. All rights reserved.
* See LICENSE for license details.
*
* @license ${license}
* @package ${packageName}
*/
`;
}
解决方案
正如ES2020Ivar
中引入的可选链接,您可以使用Nullish 合并运算符 (??) ,如果左侧操作数是or ,则返回右侧。null
undefined
function getLeadingComments(context) {
const contextOptions = context?.options[0];
const description =
contextOptions?.description ?? "React based Progressive Web App";
const author = contextOptions?.author ?? "";
const license = contextOptions?.license ?? "OSL-3.0";
const packageName = contextOptions?.package ?? "Powered by My Project";
return `
/*
* ${description}
*
* Copyright © ${author}. All rights reserved.
* See LICENSE for license details.
*
* @license ${license}
* @package ${packageName}
*/
`;
}
getLeadingComments({
options: [
{
description: "Incoming Data Description",
author: "Incoming Data Author",
license: "Incoming Data License",
package: "Incoming Data Package",
},
],
});
推荐阅读
- r - 从两个数据集中选择特定数字的值
- android - 方法引发了“java.lang.NullPointerException”异常。无法评估 java.time.LocalDateTime.toString()
- arrays - Swift Array - “Int.random(in: 0...25)”和“randomElement()”之间的区别
- joomla - 如何将通知推送到 Joomla 插件
- python - 如何在函数参数中解压缩树状结构(如 js 对象或 json)?
- wso2 - 访问 WSO2 产品的 H2 嵌入式数据库
- pyqt5 - 类之间的 PyQt5 信号导致锁定
- jenkins - 在 Jenkins 中附加可能不存在的环境变量
- android - 如何在android中应用rgba渐变
- python - 迈克尔逊干涉仪条纹计数器