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

如何在jq的range循环中更新外部定义的$runner变量

问题描述

输入为1时,希望在使用jq的range循环过程中更新$runner变量的值,但当前代码无法实现预期效果:

. as $index | 1 as $runner | label $out | range($index; 20) 
| if (. == 10) then break $out else "dx" + ($runner|tostring) | ($runner+1) as $runner | . end
解决方案

jq中的变量是不可变的,管道内的($runner+1) as $runner只会在当前管道节点生效,不会改变外部的$runner变量。要实现循环中累积更新变量的效果,推荐以下两种方式:

方式一:使用reduce累积状态

. as $index
| reduce range($index; 20) as $i (1;  # 初始$runner值设为1
    if $i == 10 then .  # 当循环索引等于10时停止,返回当前累积值
    else "dx\(.|tostring)", . + 1  # 输出目标字符串,同时将$runner加1
    end
)

输入为1时,会输出dx1到dx9的字符串序列,$runner会从1累积到10,索引到10时停止循环。

方式二:使用递归函数实现循环

def loop($current_index; $runner):
    if $current_index >= 10 then empty
    else "dx\($runner|tostring)", loop($current_index + 1; $runner + 1)
    end;

. as $index | loop($index; 1)

递归函数会从输入的起始索引开始,每次同时递增索引和$runner,直到索引达到10时停止,输出对应字符串序列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 04:26:02