0

想不出更好的方式来表达这个标题。我正在尝试找出解决此问题的最佳方法。我有一个构造我的 JSON 调用的函数,它工作得很好。但这似乎真的很乱,因为有一些冗余代码。我试图想出一种更好的方法来构建这些多重 else if 以及是否有更好的方法来构建我的 JSON 调用。

function getUsers() {

    if($.cookie('usernameCookie') && $.cookie('userHeight') && $.cookie('userWeight')){                
    var queryUsers = "/user/services/usercenters.json?" + "zipcode=" + zip + "&height=" + heightCookie + "&paymentTypes=" + paymentFilter + "&userTypes=" + userFilter + "&officeTypes=" + officeFilter;            
    } else if($.cookie('usernameCookie') && $.cookie('userHeight')){
    var queryUsers = "/user/services/usercenters.json?" + "zipcode=" + zip + "&height=" + heightCookie + "&paymentTypes=" + paymentFilter;
    } else if($.cookie('usernameCookie')){
    var queryUsers = "/user/services/usercenters.json?" + "zipcode=" + zip + "&height=" + heightCookie;       
    } else {
    var queryUsers = "/user/services/usercenters." + zip + ".json";    
    }

}

如果非常感谢任何帮助。

4

3 回答 3

2
var a = $.cookie('usernameCookie');
var b = $.cookie('userHeight');
var c = $.cookie('userWeight');

if (a) {
     var queryUsers = "/user/services/usercenters.json?"
  if (b) {
       queryUsers += //code here
     if (c) {
         queryUsers += //code here
     }
  }
} else {
   //code here
}
于 2013-10-11T12:45:14.957 回答
0

我做了一个简化的 if 语句,这也减少了字符串构建中的冗余。

function getUsers() {
    var name = $.cookie('usernameCookie'),
        height = $.cookie('userHeight'),
        weight = $.cookie('userWeight'),
        queryUsers = "/user/services/usercenters.json?zipcode=" + zip;

    if (name) {
        queryUsers += "&height=" + heightCookie; // I've put this here since every instance that had a name also had the height
        if (height && weight) {
            queryUsers += "&paymentTypes=" + paymentFilter + "&userTypes=" + userFilter + "&officeTypes=" + officeFilter;
        } else if (height && !weight) {
            queryUsers += heightCookie + "&paymentTypes=" + paymentFilter;
        }
    } else {
        queryUsers = "/user/services/usercenters." + zip + ".json";
    }
}

http://jsfiddle.net/Villike/mLG8S/1/

于 2013-10-11T14:22:38.450 回答
0
function getUsers() {
    var queryUsers;
    if($.cookie('usernameCookie')) {                
        queryUsers = '/user/services/usercenters.json?'+zipcode;
        if($.cookie('userHeight')){
            queryUsers += "&height="+heightCookie;
        }
        if($.cookie('userWeight')) {
            queryUsers += "&height="+widthCookie;
        }
        // ... etc.
    }
    else {
        queryUsers = '/user/services/usercenters.' + zip + '.json';    
    }

    // queryusers done...
}
于 2013-10-11T12:51:33.990 回答