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循环,循环体内必须有true或false返回值。
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进行数组循环的各种方法,包括for循环、for...in循环、for...of循环、forEach方法及every方法,并展示了每种方法的具体用法和输出结果。
669

被折叠的 条评论
为什么被折叠?



