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

减法运算符如何触发数组到数字的转换?

Why 10 - [4] Returns 6 (And How It Differs From [4] + 10)

Great question! You already nailed the behavior of the addition operator, so let's break down exactly what's happening with subtraction—since it follows a totally different set of type conversion rules.

The Key Difference: Addition vs. Subtraction Type Hints

First, remember JavaScript uses ToPrimitive conversion to turn objects (like arrays) into primitive values before applying operators. The operator determines what "hint" is passed to ToPrimitive, which changes the conversion order:

  • For the + operator (when it’s not purely numeric), the hint is default—which for arrays acts like the string hint. It tries toString() first (since an array’s valueOf() just returns the array itself, which isn’t a primitive). That’s why [4] + 10 becomes "4" + "10" = "410".
  • For the - operator, it’s strictly a numeric operation. The hint passed to ToPrimitive is number, which flips the conversion steps entirely.

Step-by-Step Breakdown of 10 - [4]

Let’s walk through each step the JS engine takes:

  1. Process the right operand [4]:
    • First, it calls [4].valueOf()—this returns the array itself (not a primitive value, so it’s ignored).
    • Next, it falls back to [4].toString(), which returns the string "4" (a valid primitive).
    • Since subtraction requires numeric values, the engine converts "4" to the number 4 using Number("4").
  2. Perform the subtraction:
    • Now we have two numbers: 10 and 4. The engine computes 10 - 4 = 6.

Quick Summary for Arrays

  • When the operator allows string coercion (like +), arrays convert to their string representation first.
  • When the operator expects a number (like -, *, /, or %), arrays first try valueOf() (which fails for arrays), then convert to string, then to a number.

That’s why you get 6 instead of something like "104"—subtraction doesn’t do string concatenation, it forces numeric conversion all the way down.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 13:54:09