请问下列javascript要怎么优化


showCollapses() {
      const { formData } = this;
      let collapseList = formData.unionTransferee ? this.restructureConfig(this.showCollapse, {
        slot: 'joint-assignee-info',
        anchor: 'jointAssigneeInfo',
        title: this.isCapitalIncrease ? '联合投资体信息' : '联合受让体信息'
      }, 3) : this.showCollapse;
      collapseList = formData.entrust ? this.restructureConfig(collapseList, {
        slot: 'member-information',
        anchor: 'memberInformation',
        title: '会员信息'
      }, -2) : collapseList;
      return collapseList;
    }

这样写代码挺好的,除了人看不太明白以外,优化的话改成if罗,看起来逻辑清晰一点,其实也差不多

你这个样的写法 有缺点 有优点
缺点是 别人看不懂
优点是 代码量少一点


showCollapses() {
  const { formData } = this;
  let collapseList = this.showCollapse;

  if (formData.unionTransferee) {
    collapseList = this.restructureConfig(this.showCollapse, {
      slot: 'joint-assignee-info',
      anchor: 'jointAssigneeInfo',
      title: this.isCapitalIncrease ? '联合投资体信息' : '联合受让体信息'
    }, 3);
  }

  if (formData.entrust) {
    collapseList = this.restructureConfig(collapseList, {
      slot: 'member-information',
      anchor: 'memberInformation',
      title: '会员信息'
    }, -2);
  }

  return collapseList;
}

这样就已经很简洁了,三目运算

不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 这个问题的回答你可以参考下: https://ask.csdn.net/questions/884758
  • 这篇博客你也可以参考下:用javascript实现图片轮播效果
  • 您还可以看一下 赵庆元老师的带你快速入门JavaScript课程中的 类型转换小节, 巩固相关知识点
  • 除此之外, 这篇博客: javascript 自动按按钮中的 javascript 自动按按钮 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:

    有的按钮里的函数有对按钮自身的操作,不能单独调用按钮里的函数。所以要用新的函数来调按钮

    <html lang="en-us">
    <head>
        <meta charset="utf-8">
        <title>usually function</title>
    </head>
    <script>
        // 按钮函数
        function test() {
            alert("点击按钮");
        };
        // 点击按钮函数
        function click_button(btn_id) {
            document.getElementById(btn_id).click();
        }
    </script>
    <!-- 加载完body后,运行load函数 -->
    <body>
        <!-- 创建按钮连接test函数 -->
        <button id="target" onclick="test()">test</button>
        
    </body>
    <script>
        // 调用 id="target" 的函数
        click_button(btn_id="target")
    </script>
    <html>
    
    

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^

showCollapses() {
  const { formData, showCollapse, isCapitalIncrease } = this;

  const jointInfoTitle = isCapitalIncrease ? '联合投资体信息' : '联合受让体信息';
  const memberInfoTitle = '会员信息';

  const jointInfoConfig = this.restructureConfig(showCollapse, {
    slot: 'joint-assignee-info',
    anchor: 'jointAssigneeInfo',
    title: jointInfoTitle,
  }, 3);

  let collapseList = formData.unionTransferee ? jointInfoConfig : showCollapse;

  if (formData.entrust) {
    collapseList = this.restructureConfig(collapseList, {
      slot: 'member-information',
      anchor: 'memberInformation',
      title: memberInfoTitle,
    }, -2);
  }

  return collapseList;
}