You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用TypeScript ES6高级函数简化生成步长为5的递增数组代码?

用ES6高级函数简化TypeScript数组生成函数

当然可以,借助ES6的数组API就能把原代码压缩到更少行数,同时逻辑完全一致:

方案一:使用Array.from

private seriesIncrementedBy5(upperLimit: number): number[] {
  return Array.from({ length: Math.floor(upperLimit / 5) + 1 }, (_, idx) => (idx + 1) * 5);
}

方案二:使用fill + map

private seriesIncrementedBy5(upperLimit: number): number[] {
  return Array(Math.floor(upperLimit / 5) + 1).fill(0).map((_, idx) => (idx + 1) * 5);
}

补充说明

  • 两种方案的核心都是先计算出需要生成的元素个数:Math.floor(upperLimit / 5) + 1,这个结果和原循环的执行次数完全匹配,保证生成的序列从5开始、步长为5,直到满足原代码的终止条件s <= upperLimit + 5。
  • 如果你的实际需求是让序列到upperLimit为止(原代码的循环条件可能多写了+5),只需要把长度计算改成Math.floor(upperLimit / 5)即可。

内容的提问来源于stack exchange,提问作者wonderful world

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 08:20:32