为什么``+ 0n`丢弃错误,但`-0n`没有呢?

发布于 2025-02-01 20:44:45 字数 344 浏览 4 评论 0 原文

以下代码在JavaScript中引发错误:

console.log(String(+0n))

但是此代码成功运行:

console.log(String(-0n))

为什么+0n 引发错误,但 -0N 却没有?

The following code throws an error in javascript:

console.log(String(+0n))

But this code runs successfully:

console.log(String(-0n))

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

很快妥协 2025-02-08 20:44:45

这样它就不会打破ASM.JS < /a>:

  • Unary +随后表达式始终是一个数字,或者导致投掷。因此,不幸的是,+在bigint上
    需要投掷,而不是与+对称:
    否则,以前的“类型” ASM.JS代码现在将是
    多态性。

AS bergi 在评论中突出显示,这是三个选项中最不好的:

  1. + bigint-- &gt; bigint:打破ASM.JS,以及其他任何使假设“ Unary Plus给出数字” 的事物;
  2. + bigint-&gt;编号:与不允许在数字和bigint之间进行隐式转换;或
  3. + bigint-&gt;错误。

So that it 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.

As Bergi highlights in the comments, this was the least bad of three options:

  1. +BigInt -> BigInt: breaks asm.js, and anything else that made the assumption "unary plus gives a Number";
  2. +BigInt -> Number: conflicts with the design decision to disallow implicit conversions between Number and BigInt; or
  3. +BigInt -> error.
云醉月微眠 2025-02-08 20:44:45

+0n 被视为+(BigInt(0)),因为Unary +表示“铸造到整数”,并且无法自动自动这样做(由于某种原因)

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

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

(您需要检查您的控制台,因为我猜这是一个堆栈尼珀的错误,阻止bigint被施放到 console.log call 中的字符串)

console.log(BigInt(-0));

+0n is treated as +(BigInt(0)), since unary + means "cast to integer", and it can't automatically do that (for some reason)

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

-0n is treated as BigInt(-0), since negative numbers can be big integers

(You need to check your console for this, since I guess there's a bug in the StackSnippets preventing BigInts from being casted to a string in the console.log call)

console.log(BigInt(-0));

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文