dart - Dart 的双重类型的奇怪行为
问题描述
以下代码输出以下结果:
double firstValue = 1.2;
print('type of firstValue: ${firstValue.runtimeType}'); // double
double secondValue = 1;
print('type of secondValue: ${secondValue.runtimeType}'); // int
print('type of secondValue parsed: ${secondValue.toDouble().runtimeType}'); // int
为什么声明的 double 值被理解为 int 值?即使我进行了显式转换, 1 值仍然是一个 int。
为什么会这样?
解决方案
我假设您使用 dart2js(包括 DartPad)看到了这些结果。
JavaScript 没有单独的int
和double
类型;它在任何地方都使用 IEEE-754 双精度浮点值。当 Dart 被转译为 JavaScript 时,Dartint
和double
类型都由相同的类型支持,并且转换回 Dart 类型需要启发式,因为类型信息丢失了。
如果您使用 Dart VM 尝试您的代码,您应该会看到预期的结果。
推荐阅读
- lua - 桌面模拟器 - 文本框 - 自动调整文本大小?
- django - 如何在 django 中检查查询是否返回某些内容?
- javascript - javascript中的join(“”)和replace(/,/g,“”)在char数组中到达“<”字符时停止-为什么?
- c - c - read() 和 fread() 返回值
- python - 如何将列表转换为嵌套字典?
- node.js - Lambda 不会执行所有的 Promise
- azure-devops - 如何在 Azure Devops 中发布对项目成员安全的 HTML 报告?
- amazon-web-services - 从 AWS S3 CLI 获取最后修改的对象
- r - 有条件地选择要在 R 中过滤的列
- sql-server - 带有表和运算符的 SQL CASE 语句