Dart2js 数字类型:确定一个值是 int 还是 double

Dart2js numeric types: determining if a value is an int or a double

我正在尝试确定函数的 dynamic 参数是否真的是 intdouble,我发现了令人惊讶的行为(至少对我而言) .

谁能解释这个输出(在 dartpad 上生成)?

foo(value) {
  print("$value is int: ${value is int}");
  print("$value is double: ${value is double}");
  print("$value runtimetype: ${value.runtimeType}");
}

void main() {
  foo(1);
  foo(2.0);
  int x = 10;
  foo(x);
  double y = 3.1459;
  foo(y);
  double z = 2.0;
  foo(z);
}

输出:

1 is int: true
1 is double: true
1 runtimetype: int
2 is int: true
2 is double: true
2 runtimetype: int
10 is int: true
10 is double: true
10 runtimetype: int
3.1459 is int: false
3.1459 is double: true
3.1459 runtimetype: double
2 is int: true
2 is double: true
2 runtimetype: int

在浏览器中无法区分 intdouble。 JavaScript 不提供任何此类区别,为此目的引入自定义类型会对性能产生重大影响,这就是为什么没有这样做的原因。

因此,对于 Web 应用程序,通常最好坚持使用 num

您可以检查一个值是否为整数,例如:

var val = 1.0;
print(val is int);

打印true

这只表示小数部分是或不是0

在浏览器中,值没有附加类型信息,因此 is intis double 似乎只是检查数字是否有小数部分并根据它做出决定一个人。