Dart - Boolean(布尔)

Dart - Boolean(布尔) 首页 / Dart入门教程 / Dart - Boolean(布尔)

Dart为Boolean数据类型提供了内置支持,DART中的布尔数据类型仅支持两个值– true和false。

语法如下所示-

bool var_name=true;  
OR  
bool var_name=false 

Boolean - 示例1

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

它将产生以下输出-

无涯教程网

true 

Boolean - 示例2

JavaScript不同,布尔数据类型仅将文字true识别为true。任何其他值都被视为false。考虑以下示例-

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

上面的代码段如果使用JavaScript运行,将显示消息"String is not empty",因为如果字符串不为空,则if构造将返回true。

但是,在Dart中,将 str 转换为 false,因为str!= true ,因此,该代码段将打印消息"Empty String"。

Boolean - 示例3

如果以上代码段以 checked 模式运行,则会引发异常。如下图所示-

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

它将以 Checked模式产生以下输出-

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:/Learnfk/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)

它将以未检查模式产生以下输出-

Empty String

注意-默认情况下, WebStorm IDE在检查模式下运行。

链接:https://www.learnfk.comhttps://www.learnfk.com/dart-programming/dart-programming-boolean.html

来源:LearnFk无涯教程网

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

Web协议详解与抓包实战 -〔陶辉〕

Elasticsearch核心技术与实战 -〔阮一鸣〕

DevOps实战笔记 -〔石雪峰〕

Kafka核心源码解读 -〔胡夕〕

重学线性代数 -〔朱维刚〕

WebAssembly入门课 -〔于航〕

容器实战高手课 -〔李程远〕

Redis源码剖析与实战 -〔蒋德钧〕

Vue 3 企业级项目实战课 -〔杨文坚〕

好记忆不如烂笔头。留下您的足迹吧 :)