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

因此,我希望此函數返回條件語句。 如果未提供任何參數,則應顯示整個語句,不帶任何數字(函數參數)。否則將參數(數字)放入語句中。 我的解決方案看起來並不優雅。

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

我不知道您要完成什么,但這是:

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