JavaScript多分支if-else if条件判断代码优化方法咨询
Optimizing Repetitive if-else Conditional Logic in JavaScript
Hey there! Let's fix up that clunky if-else block and make your code cleaner, more maintainable, and less error-prone. First, let's spot a couple of issues in the original code that we can address:
- The final
else ifcondition (lang !== "tr" || "en" || "ar") is logically incorrect—since non-empty strings are truthy, this condition will always evaluate totrue, which isn't what you intended. - You're repeating assignments like
lang = "en"which are redundant since the value is already the same.
Here's the optimized version:
const locale = window.location.origin; const pathName = window.location.pathname; // Define allowed languages in an array for easy maintenance const allowedLanguages = ["tr", "en", "ar"]; // Get the first path segment, default to empty string if it doesn't exist let lang = pathName.split("/")[1] || ""; // Set default lang to "tr" if empty, else check if it's in allowed list if (lang === "") { lang = "tr"; } else if (!allowedLanguages.includes(lang)) { // Fallback to stored language if current lang isn't allowed lang = localStorage.getItem('VueAppLanguage'); } // Optional: Add a final fallback if localStorage returns null // lang = lang || "tr"; console.log(lang); const res = await axios.get(`${locale}/${lang}/categories`);
Why this works better:
- Maintainable allowed languages: Adding a new supported language only requires updating the
allowedLanguagesarray—no need to add moreelse ifclauses. - Fixed logical error: The
!allowedLanguages.includes(lang)correctly checks if the detected language isn't in our approved list. - Reduced redundancy: We eliminate unnecessary assignments where
langwas set to the same value it already had. - Cleaner syntax: Using template literals (
${locale}/${lang}/categories) makes the URL string easier to read than concatenation with+.
If you want to make it even more concise, you could condense the logic into a single line with ternary operators, but the above version keeps readability a priority—always a win for future you (or other developers working on this code!).
内容的提问来源于stack exchange,提问作者Liza
相关产品推荐
相关产品推荐

