网站开发竞价单页,如何在自己的服务器上做网站,网络营销的技巧有哪些,浙江人事考试网TypeScript 循环语句详解
TypeScript 的循环语句语法与 JavaScript 完全相同#xff0c;包括 for、for...of、for...in、while、do...while#xff0c;以及数组的高阶方法#xff08;如 forEach、map 等#xff09;。TypeScript 的优势在于类型推断和类型检查#xff0c;…TypeScript 循环语句详解TypeScript 的循环语句语法与 JavaScript 完全相同包括for、for...of、for...in、while、do...while以及数组的高阶方法如forEach、map等。TypeScript 的优势在于类型推断和类型检查能确保循环中变量的类型安全尤其在遍历数组、对象或联合类型时。1. for 循环经典三段式语法for(leti0;ilength;i){// 代码}示例for(leti:number0;i5;i){console.log(第${i1}次循环);}// TS 会自动推断 i 为 number无需显式注解for(leti0;i5;i){console.log(i*2);}2. for…of 循环遍历可迭代对象的值最常用在数组、字符串、Set、Map 等可迭代对象上。constcolors:string[][red,green,blue];for(constcolorofcolors){// color 类型被推断为 stringconsole.log(color.toUpperCase());// 安全调用字符串方法}conststr:stringTypeScript;for(constcharofstr){console.log(char);// char 类型为 string}优势简洁、安全推荐用于数组遍历。3. for…in 循环遍历对象的键遍历对象的可枚举属性键包括原型链上的。interfaceUser{name:string;age:number;}constuser:User{name:Alice,age:25};for(constkeyinuser){// key 类型被推断为 keyof User即 name | ageconsole.log(${key}:${user[key]});}// 注意for...in 会遍历原型链实际使用时常结合 hasOwnProperty 检查for(constkeyinuser){if(Object.hasOwnProperty.call(user,key)){console.log(user[keyaskeyofUser]);}}注意不推荐用于数组遍历会遍历索引作为字符串可能导致意外。4. while 循环letcount:number0;while(count5){console.log(count);count;}5. do…while 循环至少执行一次letinput:string;do{inputprompt(请输入 quit 退出)||;// 假设浏览器环境}while(input!quit);console.log(已退出);6. 数组高阶方法推荐在 TS 中优先使用这些方法类型安全且代码更函数式、更易读。方法用途返回值示例forEach遍历无返回值voidarr.forEach(item console.log(item));map转换数组新数组arr.map(x x * 2);filter过滤新数组arr.filter(x x 10);find查找第一个匹配元素元素或 undefinedarr.find(x x 10);some是否存在匹配booleanarr.some(x x 10);every是否全部匹配booleanarr.every(x x 0);reduce归约累加、汇总任意类型arr.reduce((sum, x) sum x, 0);TS 类型优势示例constnumbers:number[][1,2,3,4,5];// map 返回类型自动推断为 number[]constdoubled:number[]numbers.map(nn*2);// filter 返回类型仍为 number[]constevens:number[]numbers.filter(nn%20);// reduce 可指定累加器类型constsum:numbernumbers.reduce((acc:number,curr)acccurr,0);7. 循环控制语句语句作用示例break跳出当前循环break;continue跳过本次循环继续下一次continue;label为循环命名可跳出外层循环带标签的 break用于嵌套循环outer:for(leti0;i3;i){for(letj0;j3;j){if(i1j1){breakouter;// 直接跳出外层循环}console.log(i,j);}}8. 最佳实践建议优先使用for...of遍历数组简洁且类型安全。避免for...in用于数组。大规模数据处理优先使用高阶方法map、filter等更符合函数式编程。避免无限循环TS 无法完全检测但逻辑上要确保退出条件。结合类型守卫在循环中缩小类型constitems:(string|number)[][a,1,b,2];for(constitemofitems){if(typeofitemstring){// item 被缩小为 stringconsole.log(item.toUpperCase());}else{// item 被缩小为 numberconsole.log(item.toFixed());}}小结循环方式速查场景推荐方式原因遍历数组值for...of或forEach/map类型安全、简洁遍历对象属性for...in或Object.keys()获取键需要索引经典for (let i 0; ...)可访问 i条件不确定次数while/do...while灵活函数式转换/过滤map、filter、reduce不可变、更易测试如果您想看实际应用示例如遍历 Map/Set、异步循环结合 async/await、或性能对比请告诉我