【问题标题】:JS: Making a better function that returns conditional statementJS:制作一个更好的返回条件语句的函数
【发布时间】:2016-01-18 19:16:59
【问题描述】:
function conditionForLinks(textNum, linkNum){
if (textNum == undefined || linkNum == undefined){
return "${typeof(contentAsset.custom.brandInfoLinkUrl) !== 'undefined' && contentAsset.custom.brandInfoLinkUrl && typeof(contentAsset.custom.brandInfoLinkText) !== 'undefined' && contentAsset.custom.brandInfoLinkText}"
}else{
return "${typeof(contentAsset.custom.brandInfoLinkUrl"+textNum+") !== 'undefined' && contentAsset.custom.brandInfoLinkUrl"+textNum+" && typeof(contentAsset.custom.brandInfoLinkText"+linkNum+") !== 'undefined' && contentAsset.custom.brandInfoLinkText"+textNum+"}"
}
};
所以我希望这个函数返回条件语句。当没有提供参数时,它应该显示没有任何数字(函数参数)的整个语句。否则将参数(数字)放在语句中。我的解决方案看起来并不优雅。
【问题讨论】:
标签:
javascript
function
conditional
【解决方案1】:
function conditionForLinks (textNum, linkNum) {
if(textNum == undefined || linkNum == undefined) {
textNum = '';
linkNum = '';
}
return ["${typeof(contentAsset.custom.brandInfoLinkUrl", textNum, ") !== 'undefined' && contentAsset.custom.brandInfoLinkUrl", textNum, " && typeof(contentAsset.custom.brandInfoLinkText", linkNum, ") !== 'undefined' && contentAsset.custom.brandInfoLinkText", textNum, "}"].join('');
}
【解决方案2】:
我不知道你想要完成什么,但这里有一些东西:
function conditionForLinks(textNum, linkNum){
textNum = (textNum == null) ? "" : textNum;
linkNum = (linkNum == null) ? "" : linkNum;
return "${typeof(contentAsset.custom.brandInfoLinkUrl"+textNum+") !== 'undefined' && contentAsset.custom.brandInfoLinkUrl"+textNum+" && typeof(contentAsset.custom.brandInfoLinkText"+linkNum+") !== 'undefined' && contentAsset.custom.brandInfoLinkText"+textNum+"}";
}