You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 if condition (lang !== "tr" || "en" || "ar") is logically incorrect—since non-empty strings are truthy, this condition will always evaluate to true, 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 allowedLanguages array—no need to add more else if clauses.
  • 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 lang was 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 18:29:03