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

三元运算符嵌套逻辑异常:始终返回空值问题求助

Troubleshooting Your Empty String Return Issue

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") returns 0 (since 8 isn't a valid octal digit) instead of the expected 8
  • This would fail both the >0 and <0 checks, 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" or 0: 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): parseInt will return NaN, which fails both comparison checks.
  • Value is null/undefined: parseInt(null) also returns NaN, 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:20:56