如何在TypeScript中从指定索引位置实现循环数组反转?
TypeScript 两类常见数据处理问题的解决方案
问题1:获取当前月份起的过去12个月名称
需求示例:若当前为七月,输出数组 ['August','September','October','November','December','January','February','March','April','May','June','July']
// 定义完整月份名称数组 const monthNames = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; function getLast12MonthsFromCurrent(): string[] { const currentMonth = new Date().getMonth(); // 0对应一月,6对应七月 const result: string[] = []; // 从当前月份的下一个月开始,循环生成12个月的名称 for (let i = 1; i <= 12; i++) { // 用取模运算处理跨年索引跳转 const targetMonthIndex = (currentMonth + i) % 12; result.push(monthNames[targetMonthIndex]); } return result; } // 示例调用(当前为七月时) console.log(getLast12MonthsFromCurrent()); // 输出:['August','September','October','November','December','January','February','March','April','May','June','July']
逻辑说明:通过getMonth()获取当前月份的0-11索引,循环12次计算目标月份索引,利用取模自动处理跨年时的索引循环(比如十二月加1后取模12得到0,对应一月),最终收集12个月份名称。
问题2:从指定索引位置执行循环反转数组
需求示例:数组 ['a','b','c','d'] 从索引2开始反转,输出 ['c','b','a','d']
function reverseFromIndex<T>(arr: T[], startIndex: number): T[] { // 参数合法性校验 if (startIndex < 0 || startIndex >= arr.length) { throw new Error('起始索引超出数组有效范围'); } // 拆分数组为需要反转的左半部分和保持原样的右半部分 const leftSegment = arr.slice(0, startIndex + 1); const rightSegment = arr.slice(startIndex + 1); // 反转左半部分后与右半部分拼接,返回新数组 return [...leftSegment.reverse(), ...rightSegment]; } // 示例调用 const myarr = ['a','b','c','d']; console.log(reverseFromIndex(myarr, 2)); // 输出:['c','b','a','d']
逻辑说明:先校验起始索引的有效性,将数组拆分为「从开头到目标索引」和「目标索引之后」的两段,反转前一段后与后一段拼接,返回全新数组(不修改原数组)。如果需要原地修改数组,可调整为直接操作原数组的对应片段。
内容的提问来源于stack exchange,提问作者Supriya
相关产品推荐
相关产品推荐

