无法想出一个更好的方法来表达这个标题。我正试图找出解决这个问题的最佳方法。我有 得到了一个构造我的JSON调用的函数,它运行得很好。但这似乎真的很混乱,因为有一些冗余的代码。我试着 想一个更好的方法来构造这些多个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";
}
}
任何帮助,如果非常感谢。
答案 0 :(得分: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
}
答案 1 :(得分: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...
}
答案 2 :(得分: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";
}
}