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

ESLint提示避免嵌套三元表达式,如何修改指定函数代码?

Fixing the Nested Ternary ESLint Error

Hey there! Let's tackle that ESLint error about nested ternaries. First, let's unpack what your original code is doing so we can replicate the logic clearly without hard-to-read nested conditionals.

Your current code iterates over this.navDropdowns and:

  • Returns true if the current index matches number and item is truthy
  • Returns !item if the index matches number but item is falsy
  • Returns false for all other indices

Here are a few clean, ESLint-compliant ways to rewrite this:

Option 1: Explicit if-else Statements (Most Readable)

This is the easiest to follow, especially for anyone else maintaining your code later:

foo(number) {
  this.navDropdowns = this.navDropdowns.map((item, index) => {
    if (index === number) {
      if (item) {
        return true;
      } else {
        return !item;
      }
    } else {
      return false;
    }
  });
}

Option 2: Simplified Single Ternary (If Logic Allows)

Wait a second—looking at your nested ternary item ? true : !item, this actually always returns true (if item is truthy, you return true; if it's falsy, !item is true). If that's intentional, you can simplify the whole thing even more:

foo(number) {
  this.navDropdowns = this.navDropdowns.map((item, index) => {
    return index === number ? true : false;
  });
}

But if you actually meant to toggle the boolean value of item when the index matches (a common use case for dropdown states), you can rewrite it with a single ternary (which ESLint allows, since it's not nested):

foo(number) {
  this.navDropdowns = this.navDropdowns.map((item, index) => {
    return index === number ? !item : false;
  });
}

Why This Works

ESLint flags nested ternaries because they hurt readability—when you stack conditionals, it's easy to misinterpret the logic at a glance. Using explicit if-else blocks or single-level ternaries keeps your code clear and maintainable.

内容的提问来源于stack exchange,提问作者Olga B

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:34:52