【问题标题】:Dart2js numeric types: determining if a value is an int or a doubleDart2js 数字类型:确定值是 int 还是 double
【发布时间】:2017-10-12 10:39:42
【问题描述】:

我正在尝试确定函数的 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

【问题讨论】:

  • 似乎runtimeType 适应了值。 z += 0.1; foo(z);2.1 runtimetype: double
  • 你是在虚拟机上运行还是通过 dart2js 运行?
  • @SethLadd 这些结果是在 dartpad 上获得的,但我们在 Chrome 中也看到了奇怪的东西(所以我认为 dart2js 参与了)。

标签: dart dart2js


【解决方案1】:

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

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

您可以使用以下示例检查值是否为整数:

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

打印true

这仅表示小数部分是否为0

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

【讨论】:

  • 感谢您的解释,但您的示例似乎不适用于 dartpad。 dartpad 是使用虚拟机还是 javascript 后端?
  • Dartpad 正在使用 dart2js 生成 JavaScript。 dartpad.dartlang.org/29693618d1199b1bc5131a627f09a0e6 可能我不够清楚。上面的代码应该打印true。它只是检查该值是否具有与 0 不同的片段部分。
  • 当你说浏览器中的int和double没有区别,那为什么3.1459 is int在dartpad上产生的结果与3.1459 is double不同呢?
  • is intis double 创建了不同的JS。我的意思是没有附加到值的类型信息可以区分该值是 int 还是 double。似乎is int 做了一些类似于我在答案中的代码中所做的事情。它只是检查值是否有片段!= 0。0.0 is int 也返回 true
  • 我将您的 cmets 纳入答案。如果您愿意,请进行编辑。
猜你喜欢
  • 1970-01-01
  • 2011-11-10
  • 2010-12-04
  • 1970-01-01
  • 1970-01-01
  • 2020-03-18
  • 2017-12-21
  • 2022-10-13
  • 1970-01-01
相关资源
最近更新 更多