简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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