请问如何简化这种写法
发布于 7 年前 作者 scai 6899 次浏览 来自 问答

//对于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 回复

遍历不能解决吗

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

}

})

var Txt = {

content0: “”,

content1: “”,

content2: “”

}

for(var key in Txt){

Txt[key] = Knowledge[TabID][key] ? “x” + Knowledge[TabID][key] + “\n” : ‘’

}

写function函数简化

回到顶部