三元运算符嵌套逻辑异常:始终返回空值问题求助
Let's work through why your ternary expression keeps returning an empty string instead of the expected <i> elements. Here are the most likely culprits and actionable fixes:
1. Missing Radix Parameter in parseInt
This is a super common gotcha! When you use parseInt without specifying the second parameter (radix), JavaScript might interpret strings starting with 0 as octal numbers instead of decimal. For example:
parseInt("08")returns0(since 8 isn't a valid octal digit) instead of the expected8- This would fail both the
>0and<0checks, leading straight to the empty string fallback.
Quick Fix: Always pass 10 as the radix to ensure consistent decimal parsing:
parseInt(item.CheeseBarrelChange, 10) > 0 ? <i className={styles.up}></i> : parseInt(item.CheeseBarrelChange, 10) < 0 ? <i className={styles.down}></i> : ''
2. Invalid or Unexpected Values in item.CheeseBarrelChange
Your expression returns empty if the parsed value is 0, NaN, null, or undefined. Let's break down these scenarios:
- Value is
"0"or0: This is actually expected per your logic (since you only want up/down indicators for positive/negative changes), but double-check if zero should have a different behavior. - Value is non-numeric (e.g.,
"abc", empty string):parseIntwill returnNaN, which fails both comparison checks. - Value is
null/undefined:parseInt(null)also returnsNaN, triggering the empty string.
Debug Step: Add a quick console log to inspect the raw and parsed values—this will reveal immediate issues:
console.log('Raw value:', item.CheeseBarrelChange); console.log('Parsed number:', parseInt(item.CheeseBarrelChange, 10));
Improved Code (with validation):
To avoid repeated parsing and handle invalid values explicitly, extract the value first:
const change = parseInt(item.CheeseBarrelChange, 10); // Handle non-numeric values upfront if (isNaN(change)) { return ''; // Or return a default icon/state if needed } return change > 0 ? <i className={styles.up}></i> : change < 0 ? <i className={styles.down}></i> : '';
3. Simplify the Ternary for Readability
Nested ternaries can be tricky to debug. Rewriting with explicit conditionals makes it easier to spot logic gaps:
const change = parseInt(item.CheeseBarrelChange, 10); if (change > 0) { return <i className={styles.up}></i>; } else if (change < 0) { return <i className={styles.down}></i>; } else { return ''; }
Start with checking the radix parameter and logging values—this will almost certainly uncover the root cause!
内容的提问来源于stack exchange,提问作者Jeffha77

