2015-10-20 41 views
2
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+"}" 
       } 
     }; 

所以我想這個函數返回條件語句。當沒有提供參數時,它應該顯示沒有任何數字(函數參數)的整個語句.Else將參數(數字)放入語句中。我的解決方案看起來不夠優雅。JS:製作更好的函數返回條件語句

回答

1

我不知道你想什麼來完成,但這裏的東西:

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