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

Power Automate中如何将连续数字数组转换为区间字符串?

在Power Automate中合并数组连续区间为指定格式字符串

1. 初始化变量

  • 创建数组变量 inputArray,赋值为目标数组:[1,2,3,4,5,8,10,11,12,13,14,15](如果原数组无序,先通过sort(variables('inputArray'))排序)
  • 创建整数变量 currentStart,初始值设为 first(variables('inputArray'))
  • 创建整数变量 currentEnd,初始值设为 variables('currentStart')
  • 创建数组变量 tempSegments,初始值为空数组(用于暂存每个区间的字符串)

2. 遍历数组处理连续区间

添加Apply to each动作,选择skip(variables('inputArray'), 1)作为遍历对象(跳过第一个元素,因为已初始化起始和结束值),当前遍历项命名为currentNum:

在循环内部执行以下操作:

  1. 判断当前元素是否连续:添加Condition动作,条件为 equals(variables('currentEnd') + 1, variables('currentNum'))
    • 如果条件为是:更新currentEnd变量的值为variables('currentNum')(扩展当前连续区间)
    • 如果条件为否:
      • 生成当前区间字符串:若currentStart等于currentEnd,则字符串为string(variables('currentStart'));否则为concat(string(variables('currentStart')), '-', string(variables('currentEnd')))
      • 将生成的字符串添加到tempSegments数组中(使用Append to array variable动作)
      • 更新currentStart和currentEnd变量的值为variables('currentNum')(开启新的区间)

3. 处理最后一个区间

遍历结束后,将最后一个未加入的区间添加到tempSegments:

  • 生成最后一个区间字符串:同样判断currentStart是否等于currentEnd,生成对应字符串
  • 使用Append to array variable动作将该字符串加入tempSegments

4. 拼接最终结果

添加Compose动作,使用join(variables('tempSegments'), ',')将tempSegments数组中的区间字符串用逗号拼接,得到最终格式的字符串(如1-5,8,10-15)

注意事项

  • 确保输入数组是升序排列的,否则连续区间判断会出错;若数组无序,先添加Sort动作处理
  • 如果数组为空,需额外添加判断逻辑避免错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 03:05:06