收藏
回答

请问如何简化这种写法

问题模块 框架类型 问题类型 操作系统 工具版本
开发者工具 小程序 需求 Windows 1.02.1902010


//对于js中很有规律的如下片段:

    Txt={}

    if (Knowledge[TabID].content0 != undefined) { Txt.Content0 = "x" + Knowledge[TabID].content0 + "\n" } else { Txt.Content0 =""}

    if (Knowledge[TabID].content1 != undefined) { Txt.Content1 = "x" + Knowledge[TabID].content1 + "\n" } else { Txt.Content1 = "" }   

    if (Knowledge[TabID].content2 != undefined) { Txt.Content2 = "x" + Knowledge[TabID].content2 + "\n" } else { Txt.Content2 = "" }

    if (Knowledge[TabID].content3 != undefined) { Txt.Content3 = "x" + Knowledge[TabID].content3 + "\n" } else { Txt.Content3 = "" }

    if (Knowledge[TabID].content4 != undefined) { Txt.Content4 = "x" + Knowledge[TabID].content4 + "\n" } else { Txt.Content4 = "" }

    if (Knowledge[TabID].content5 != undefined) { Txt.Content5 = "x" + Knowledge[TabID].content5 + "\n" } else { Txt.Content5 = "" }



//  如何简化写法? 

最后一次编辑于  03-17  (未经腾讯允许,不得转载)
邀请回答
复制链接收藏投诉关注问题回答

4 个回答

  • sheng
    sheng
    03-18


    Page({


    data: {},


    onLoad: function() {

    var Knowledge = {

    TabID_1: {

    content0: 'content0',

    content1: 'content1',

    content2: 'content2',

    content4: 'content4'

    },

    TabID_2: {

    content0: 'content0',

    content2: 'content2'

    }

    }, Txt = {};

    Txt = this.getTxtWith(Knowledge, 'TabID_1', 5);

    console.log(Txt);

    Txt = this.getTxtWith(Knowledge, 'TabID_2', 8);

    console.log(Txt);

    },


    getTxtWith: function(knowledge, tabId, length) {

    var txt = {};

    for (var i = 0; i < length; i++) {

    var o = knowledge[tabId][`content${i}`] || false;

    txt[`Content${i}`] = o ? `x${o}\n` : ''

    }

    return txt

    }


    })


    03-18
    赞同 2
    回复 3
    • 包魁
      包魁
      03-18

       

       [`content${i}`] 识别不出来


      03-18
      回复
    • sheng
      sheng
      03-19回复包魁

      不会吧 https://developers.weixin.qq.com/s/WJQGxYm67V6Q

      03-19
      1
      回复
    • 包魁
      包魁
      03-19回复sheng

       现在可以了,不知道什么原因,可能是引号格式问题。

      03-19
      回复
  • 铭锋科技
    铭锋科技
    03-17

    写function函数简化

    03-17
    赞同 1
    回复
  • 拾忆
    拾忆
    03-17

    var Txt = {

    content0: "",

    content1: "",

    content2: ""

    }

    for(var key in Txt){

    Txt[key] = Knowledge[TabID][key] ? "x" + Knowledge[TabID][key] + "\n" : ''

    }


    03-17
    赞同 1
    回复 2
    • 包魁
      包魁
      03-18

       

       佩服佩服!


      03-18
      回复
    • 拾忆
      拾忆
      03-18回复包魁
      😳😳😳😳😳
      03-18
      回复
  • 这都申请了
    这都申请了
    03-18

    遍历不能解决吗

    03-18
    赞同 1
    回复