//对于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 = "" }
// 如何简化写法?
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
}
})
[`content${i}`] 识别不出来
不会吧 https://developers.weixin.qq.com/s/WJQGxYm67V6Q
现在可以了,不知道什么原因,可能是引号格式问题。
遍历不能解决吗
var Txt = {
content0: "",
content1: "",
content2: ""
}
for(var key in Txt){
Txt[key] = Knowledge[TabID][key] ? "x" + Knowledge[TabID][key] + "\n" : ''
}
佩服佩服!
写function函数简化