[英]How should I refactor this nested IF statement?
我有這個 function 有超過 3 個嵌套 if 語句(4 個嵌套 If 在函數中)。 我正在嘗試解決聲納問題,它說要refactor this code to not nest more than 3 IF/FOR/WHILE/TRY statements
。 我四處尋找,但找不到任何有用的東西,可以減少嗎? - 如果是這樣,我將如何 go 這樣做? 任何反饋表示贊賞
這是 function
function find(animals) {
var animalsCode = getByanimals(animals);
if (typeof animalsCode !== 'undefined' && !isanimalsSupported(animalsCode)) ---> Nesting 1{
var url = $('.menu-select-animals li[data-animals="' + animalsCode + '"] a').attr('href');
var newQuery = '';
if (url) { ---->Nesting 2
var redirectQuery = '';
if (window.location.search) {
//some logic
}
if (url.indexOf('?') > -1) { ---->Nesting 3
//some logic
if (typeof join[1] !== 'undefined') { ---->Nesting 4
//some code
}
}
if (typeof mergedQueries !== 'undefined');
}
} else {
//some code
}
else {
handleanimals();
}
}
return {
handleanimals();
},
windows: function() {
if (typeof theSrc !== 'undefined') {
// some logic
}
if (typeof animalsCheckTheSrc !== 'undefined') {
if (animalsCookie !== animalsCheckTheSrc) {
// some logic
}
checkanimalsCookie(animalsCheckTheSrc);
} }}};
})(jQuery);
很難對您的 function 進行推理,因為它不返回任何內容。 我將很難跟蹤依賴於這些僅像這樣的副作用功能的程序的流程。
但是,您可能會做的一件事是進一步分解這個 function 並開始使用返回值。 例如,拆分這段代碼,並在新的 function 中返回 redirectURL。
if (redirectURL) { ---->Nesting 2
var pageQuery = '';
var redirectQuery = '';
if (window.location.search) {
pageQuery = window.location.search.substr(1).split('&');
}
if (redirectURL.indexOf('?') > -1) { ---->Nesting 3
var redirectSplit = redirectURL.split('?');
redirectURL = redirectSplit[0];
if (typeof redirectSplit[1] !== 'undefined') { ---->Nesting 4
redirectQuery = redirectSplit[1].split('&');
}
}
var mergedQueries = com.trp.fai.utility.mergeStringArrays(redirectQuery, pageQuery);
if (typeof mergedQueries !== 'undefined' && mergedQueries.length > 0) {
newQuery = '?' + mergedQueries.join('&');
}
} else {
redirectURL = 'http://corporate.troweprice.com';
newQuery = '?src=' + countryCode;
}
如果您需要返回多個項目,您可以使用全局變量或返回 object 並在另一側對其進行解構。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.