首页 > 解决方案 > 符合 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}
 */
`;
}

标签: javascriptarraysreactjsecmascript-6eslint

解决方案


正如ES2020Ivar中引入的可选链接,您可以使用Nullish 合并运算符 (??) ,如果左侧操作数是or ,则返回右侧。nullundefined

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",
    },
  ],
});

推荐阅读