【问题标题】:how to check if a number is a BigInt in javascript如何在javascript中检查一个数字是否是BigInt
【发布时间】:2021-05-30 13:11:31
【问题描述】:

我想检查一个数字是否是大小可接受的 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 语句中实现测试,而不是在我的函数中
有人可以帮我吗?

【问题讨论】:

  • 您可以在 if 语句中插入函数调用。

标签: javascript bigint


【解决方案1】:

您可以使用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!");
  }
});

【讨论】:

    【解决方案2】:

    如果我很好地理解了您的问题,三元运算符可以为您提供帮助:

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

    根据您的数字是否为 bigint,您的变量“isTernay”中将包含真或假。

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

    0n === 0
    // ↪ false
    
    0n == 0
    // ↪ true
    

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

    【讨论】:

    • 在布尔情况下你甚至不需要三进制(即你写cond ? true : false的地方),写cond就足够了。问题出在 try..catch 上,它不能被内联。
    【解决方案3】:

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

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

    然后您就可以简单地致电myNum.bigInt 进行检查。

    注意:3.bigInt 将不起作用,因为 3. 被视为数字,因此您可以这样做:

    (3).bigInt
     3 .bigInt
    

    或在变量上使用它

    【讨论】:

      猜你喜欢
      • 2020-01-28
      • 2011-02-08
      • 2010-10-20
      • 2010-09-16
      • 1970-01-01
      • 2010-10-20
      • 1970-01-01
      相关资源
      最近更新 更多