您的位置:58编程 > typescript for循环 TypeScript do ... while循环

typescript for循环 TypeScript do ... while循环

2023-03-20 16:33 TypeScript教程

typescript for循环 TypeScript do ... while循环

typescript for循环

for循环是一种常见的循环控制结构,它可以重复执行一个或多个语句,直到某个条件不再满足。TypeScript中的for循环有三种形式:for、for…in和for…of。

首先,我们来看看最常用的 for 循环。它有三个部分:初始化语句、条件表达式和迭代语句。它的语法如下所示:

for (initialization; condition; iteration) { 
    statement 
} 

在 for 循环中,首先会执行 initialization 语句,然后会检查 condition 是否为 true。如果 condition 为 true,就会执行 statement 语句块中的代码。然后会执行 iteration 语句,并再次检查 condition 是否为 true。如此往复直到 condition 不再为 true 为止。

 
let arr = [1, 2, 3, 4]; 
for (let i = 0; i < arr.length; i++) { 
    console.log(arr[i]); // 1 2 3 4 
}  

上面代码中我们使用 for 循环遍历了一个数字数组 arr ,并将数字依次输出到了 console 控制台中。在这里我们使用了 let 关键字声明了一个 i 索引变量;initialization 部分将 i 置 0 ;condition 部分是 i < arr.length ;iteration 部分是 i++ ;statement 部分是 console.log(arr[i]) ;

其次是 for…in 循环。它用于遍历对象的属性或者数字数组的元素。它的语法如下所示:

 
for (variable in object) {   // variable 是 object 的属性名   // object 是要遍历的对象   // statement 是要执行的语句   statement   }   

例如我们想要遍历一个对象 obj 的属性 name、age、gender :

  let obj = {name: 'John', age: 20, gender: 'male'};   for (let key in obj) {     console.log(key + ':' + obj[key]);   } 

上面代码中我们使用 for…in 循环遍历了对象 obj 的属性 name、age、gender ;并将 key 和 value 用 : 连接在一起输出到了 console 控制台中。在这里我们使用 let 关键字声明了一个 key 变量来保存当前遍历的属性名;object 部分是 obj ;statement 部分是 console.log(key + ':' + obj[key]) ;

TypeScript do ... while循环

TypeScript do ... while循环

do ... while循环类似于while循环,只是do ... while循环不会在第一次循环执行时评估条件。但是,将对后续迭代评估条件。换句话说,代码块将在do ... while循环中至少执行一次。

语法

do {
   //statements 
} while(condition)

流程图

示例:do ... while

var n:number = 10;
do { 
   console.log(n); 
   n--; 
} while(n>=0); 

在编译时,它将生成以下JavaScript代码:

//Generated by typescript 1.8.10
var n = 10;
do {
   console.log(n);
   n--;
} while (n >= 0);

该示例以相反的顺序打印0到10之间的数字。

10 
9 
8 
7 
6 
5 
4 
3 
2 
1 
0
阅读全文
以上是58编程为你收集整理的typescript for循环 TypeScript do ... while循环全部内容。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。
相关文章
© 2024 58编程 58biancheng.com 版权所有 联系我们
桂ICP备12005667号-32 Powered by CMS