为什么 `+0n` 会抛出错误而 `-0n` 不会?

Why `+0n` throws an error but `-0n` does not?

以下代码在 javascript 中抛出错误:

console.log(String(+0n))

但是这段代码运行成功:

console.log(String(-0n))

为什么 +0n 会抛出错误而 -0n 不会?

+0n 被视为 +(BigInt(0)),因为一元 + 表示“转换为整数”,并且它不能自动执行此操作(出于某种原因)

console.log(+(BigInt(0)));

-0n 被视为 BigInt(-0),因为负数可以是大整数

(你需要为此检查你的控制台,因为我猜 StackSnippets 中有一个错误阻止 BigInts 被转换为 console.log call 中的字符串)

console.log(BigInt(-0));

这样 doesn't break asm.js:

  • Unary + followed by an expression is always either a Number, or results in throwing. For this reason, unfortunately, + on a BigInt needs to throw, rather than being symmetrical with + on Number: Otherwise, previously "type-declared" asm.js code would now be polymorphic.

正如评论中 Bergi 强调的那样,这是三个选项中最不糟糕的:

  1. +BigInt -> BigInt:中断 asm.js,以及做出假设的任何其他内容 “一元加号给出一个数字”
  2. +BigInt -> Number:与 design decision 冲突以禁止 Number 和 BigInt 之间的隐式转换;或
  3. +BigInt -> 错误。