Dart语言教程:bool布尔数据类型

2019-06-2215:05:50编程语言入门到精通Comments2,613 views字数 1124阅读模式

Dart为布尔数据类型提供内置支持,Dart中的布尔数据类型仅支持两个值 - truefalse。关键字bool用于表示Dart中的布尔文字。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13747.html

在Dart中声明布尔变量的语法,如下所示 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13747.html

bool var_name = true;  
// 或者
bool var_name = false
Dart

示例1文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13747.html

void main() { 
   bool test; 
   test = 12 > 5; 
   print(test); 
}
Dart

执行上面示例代码,得到以下结果 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13747.html

true
Shell

示例2文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13747.html

与JavaScript不同,布尔数据类型仅将文字true识别为true。任何其他值都被视为false。考虑以下示例 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13747.html

var str = 'abc'; 
if(str) { 
   print('String is not empty'); 
} else { 
   print('Empty String'); 
}
Dart

如果在JavaScript中运行,上面的代码段将打印消息 - "String is not empty",因为如果字符串不为空,if结构将返回true文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13747.html

但是,在Dart中,str被转换为false,因为str != true。因此,代码段将打印消息 - "Empty String"(在未检查模式下运行时)。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13747.html

示例3文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13747.html

如果以已检查模式运行,上面的代码片段将引发异常。如以下说明 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13747.html

void main() { 
   var str = 'abc'; 
   if(str) { 
      print('String is not empty'); 
   } else { 
      print('Empty String'); 
   } 
}
Dart

它将在已检查模式下产生以下输出 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13747.html

Unhandled exception: 
type 'String' is not a subtype of type 'bool' of 'boolean expression' where 
   String is from dart:core 
   bool is from dart:core  
#0 main (file:///D:/Demos/Boolean.dart:5:6) 
#1 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:261) 
#2 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148)
Shell

它将以检查模式生成以下输出 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13747.html

Empty String
Shell

注 - 默认情况下,WebStorm IDE以选中模式运行。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13747.html

原文出自【易百教程】,商业转载请联系作者获得授权,非商业转载请保留原文链接:https://www.yiibai.com/dart/dart_programming_boolean.html#article-start文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13747.html

文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/13747.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/ymba/13747.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定