我对ES6并不是很在行,因此我希望能得到一些帮助:c.我如何优化这段代码以获得更好的视觉效果?我已经尝试了下面的解决方案,但是,我确信我可以在这里使用像.map()或类似的数组Array.prototype方法。这里的想法是确保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}
*/
`;
}发布于 2021-04-08 18:00:47
正如Ivar所说,可选链接是在ES2020中引入的,如果左侧操作数为null或undefined,则可以使用Nullish coalescing operator (??)返回右侧。
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",
},
],
});https://stackoverflow.com/questions/67001452
复制相似问题