TypeScript_For循环

let testArray = [20, "string", true, "hahha"];
  • for循环

for循环其实是标准的C语言风格语法。

for (var i = 0; i < testArray.length; i ++) {
    console.log("数组的值:"+testArray[i]); 
}
// 数组的值:20
// 数组的值:string
// 数组的值:true
// 数组的值:hahha

  • for…in循环
for (let index in testArray) {
      console.log("数组的下标:"+index);
    }
/*
数组的下标:0
数组的下标:1
数组的下标:2
数组的下标:3
*/

  • for…of循环
for (let value of testArray) {
      console.log("数组的值:"+value);
    }
/*
数组的值:20
数组的值:string
数组的值:true
数组的值:hahha
*/

  • forEach循环
    forEach其实是JavaScript的循环语法,TypeScript作为JavaScript的语法超集,当然默认也是支持的。
testArray.forEach((value, index, array)=>{
      console.log("value:"+value+"--index:"+index);
      console.log(array);
    });
/*
打印日志:
 value:20--index:0
 (4) [20, "string", true, "hahha"]
 value:string--index:1
 (4) [20, "string", true, "hahha"]
 value:true--index:2
 (4) [20, "string", true, "hahha"]
 value:hahha--index:3
 (4) [20, "string", true, "hahha"]
*/

  • every循环
    every也是JavaScript的循环语法,TypeScript作为JavaScript的语法超集,当然默认也是支持的。因为forEach在iteration中是无法返回的,所以可以使用every来取代forEach
    every循环,循环体内必须有truefalse返回值。
testArray.every((value, index, array) => {
      return true;//类似于continue,持续当前循环
    });
 testArray.every((value, index, array) => {
      console.log("index:"+index+"--value:"+value);
      return false; //类似于break,跳出当前循环
    });
 // 打印日志
 // index:0--value:20

Typescript的官方文档 Iterators and Geneators

猜你喜欢

转载自blog.csdn.net/FlyingKuiKui/article/details/80547733