【问题标题】: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+"}";
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-02
        • 1970-01-01
        • 2011-02-25
        • 2019-05-07
        • 2022-01-03
        • 1970-01-01
        • 2012-03-28
        • 1970-01-01
        相关资源
        最近更新 更多