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

为何JavaScript中parseInt("0x")返回NaN而非0?

Why does parseInt("0x") return NaN instead of 0?

Great question! This behavior boils down to how parseInt handles numeric prefixes and validates the characters that follow them. Let’s break it down with your examples to make it clear:

1. How parseInt works with prefixes

parseInt first scans the input string to detect a numeric prefix that indicates a non-decimal base:

  • Hexadecimal numbers are prefixed with 0x or 0X (this is a universally recognized prefix for parseInt even without specifying a base)
  • While 0b is the prefix for binary numbers, parseInt doesn’t recognize it by default—you’d need to explicitly pass 2 as the second parameter to parse binary strings

When parseInt detects a valid, recognized prefix, it requires at least one valid digit after the prefix to complete the parsing. If there are no valid digits following the prefix, the entire operation fails and returns NaN.

2. Breaking down your examples

  • parseInt("024x2") // 24: No special recognized prefix here (it’s not 0x), so parseInt parses as decimal. It reads 0, 2, 4 (all valid decimal digits), then stops at x which isn’t a digit. The result is 24.
  • parseInt("0b") // 0: Since 0b isn’t a default recognized prefix, parseInt treats this as a decimal string. It reads the first character 0, then hits b which isn’t a decimal digit, so it stops and returns the valid digit it found: 0.
  • parseInt("0x") // NaN: Here, parseInt immediately detects the hexadecimal prefix 0x. But after the prefix, there are no valid hexadecimal digits (0-9, a-f, A-F) to parse. Since the hex prefix mandates trailing digits to form a valid number, the parsing fails entirely, hence NaN.

Key takeaway

The difference hinges on whether the prefix is natively recognized by parseInt and whether that prefix requires trailing digits. The 0x prefix triggers hexadecimal mode, which can’t form a valid number without digits after it. The 0b prefix doesn’t trigger binary mode by default, so it falls back to parsing the leading 0 as a decimal digit.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:36:21