简体   繁体   English

JS:制作一个更好的函数以返回条件语句

[英]JS: Making a better function that returns conditional statement

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+"}"
                }
        };

So I want this function to return the conditional statement. 因此,我希望此函数返回条件语句。 When no arguments are provided it should display the whole statement without any numbers(function arguments).Else put the arguments(numbers) in the statement. 如果未提供任何参数,则应显示整个语句,不带任何数字(函数参数)。否则将参数(数字)放入语句中。 My solution does not looks elegant. 我的解决方案看起来并不优雅。

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('');
}

I don't know exactly what you are trying to accomplish but here is something: 我不知道您要完成什么,但这是:

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+"}";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM