收藏
回答

请问如何简化这种写法

框架类型 问题类型 操作系统 工具版本
小程序 需求 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 = "" }



//  如何简化写法? 

回答关注问题邀请回答
收藏

4 个回答

  • sheng
    sheng
    2019-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

    }


    })


    2019-03-18
    有用 2
    回复 3
    • 2019-03-18

       

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


      2019-03-18
      回复
    • sheng
      sheng
      2019-03-19回复

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

      2019-03-19
      1
      回复
    • 2019-03-19回复sheng

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

      2019-03-19
      回复
  • 这都申请了
    这都申请了
    2019-03-18

    遍历不能解决吗

    2019-03-18
    有用 1
    回复
  • 拾忆
    拾忆
    2019-03-17

    var Txt = {

    content0: "",

    content1: "",

    content2: ""

    }

    for(var key in Txt){

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

    }


    2019-03-17
    有用 1
    回复 2
    • 2019-03-18

       

       佩服佩服!


      2019-03-18
      回复
    • 拾忆
      拾忆
      2019-03-18回复
      😳😳😳😳😳
      2019-03-18
      回复
  • 铭锋科技
    铭锋科技
    2019-03-17

    写function函数简化

    2019-03-17
    有用 1
    回复
登录 后发表内容