如何在 javascript 中检查数字是否为 BigInt

how to check if a number is a BigInt in javascript

我想检查一个数字是否是可接受大小的 BigInt if 语句

我知道有解决办法

function isBigInt(x) {
    try {
        return BigInt(x) === x; // dont use == because 7 == 7n but 7 !== 7n
    } catch(error) {
        return false; // conversion to BigInt failed, surely it is not a BigInt
    }
}

但我想直接在我的 if 语句中实现测试,而不是在我的函数中
有人可以帮我吗?

您可以使用 typeof。如果数字是 BigInt,则 typeof 将是“bigint”。否则,它将是“数字”

var numbers = [7, BigInt(7), "seven"];
numbers.forEach(num => {
  if (typeof num === "bigint") {
    console.log("It's a BigInt!");
  } else if (typeof num === "number") {
    console.log("It's a number!");
  } else {
    console.log("It's not a number or a BigInt!");
  }
});

如果我理解你的问题,三元运算符可以帮助你:

...
const isTernary = BigInt(x) === x ? true : false
...

您的变量“isTernay”中的值要么是 true 要么是 false,具体取决于您的数字是否为 bigint。

并且 BigInt 对象并不严格等于 Number,但可以在弱相等的意义上。

0n === 0
// ↪ false

0n == 0
// ↪ true

访问:https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/BigInt 了解更多关于 BigInt

一个简单的解决方案就是(假设您只使用数字):

Number.prototype.bigInt = false
BigInt.prototype.bigInt = true

然后你可以简单地调用 myNum.bigInt 来检查。

注意:3.bigInt 不起作用,因为 3. 被认为是一个数字,所以你可以这样做:

(3).bigInt
 3 .bigInt

或在变量上使用它