ESLint提示避免嵌套三元表达式,如何修改指定函数代码?
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
trueif the current index matchesnumberanditemis truthy - Returns
!itemif the index matchesnumberbutitemis falsy - Returns
falsefor 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

