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]) ;
do ... while循环类似于while循环,只是do ... while循环不会在第一次循环执行时评估条件。但是,将对后续迭代评估条件。换句话说,代码块将在do ... while循环中至少执行一次。
do { //statements } while(condition)
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
TypeScript 字符串concat()方法concat()方法添加两个或多个字符串并返回一个新的单个字符串。语法string.concat(...
命名空间是对相关代码进行逻辑分组的一种方法。这是内置于TypeScript中的,与JavaScript不同,其中变量声明进入全局范围,如果在...
很多网站都有提供一些很不错的JSON在线校验工具,我们也提供了一些JSON在线工具:Excel/csv数据转json格式工具这是一款可将Excel...
HTML DOM del 对象del 对象 del 对象代表了HTML文档中已被删除的文本。 del 元素定义文档中已被删除的文本。 del 元素经常与 ins...
HTML DOM Image 对象Image 对象Image 对象代表嵌入的图像。img 标签每出现一次,一个 Image 对象就会被创建。Image 对象属性W3C:...
HTML DOM Input Email 对象Input Email 对象Input Email 对象是 HTML5 新增的。Input DatetimeLocal 对象表示使用 type="email" ...
HTML DOM Textarea 对象Textarea 对象Textarea 对象代表 HTML 表单中的一个文本域 (text-area)。HTML 表单的每一个 textarea 标...
Body link 属性 Body 对象定义和用法 link 属性可设置或者返回 body 元素的 link属性值。 link 属性指定了文档中链接未被点击访...