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

批处理脚本中如何将数组作为子例程参数传递?

问题分析

原代码无法得到预期结果的原因有两点:

  1. 数组传递错误:call :whatever %array1%试图读取array1变量的值,但你从未定义过这个变量,实际需要传递的是数组的名称字符串(array1)而非变量值。
  2. 变量解析错误:子例程中%1[1]会被批处理直接解析为「参数内容+字符串[1]」,不会自动拼接成数组变量名(如array1[1])去读取对应元素。
解决方案

方法一:使用延迟扩展(推荐,代码更简洁)

利用已开启的EnableDelayedExpansion,通过延迟扩展语法动态解析数组变量:

@echo off

setlocal EnableDelayedExpansion

set array1[1]=1
set array1[2]=2

set array2[1]=3
set array2[2]=4

call :whatever array1
call :whatever array2

goto :eof

:whatever
echo value of first array element is !%1[1]!
echo value of second array element is !%1[2]!
goto :eof

关键说明:

  • 调用子例程时直接传递数组名称(array1/array2),而非未定义的变量值。
  • !%1[1]!的解析逻辑:先通过%1替换为数组名,形成array1[1],再通过延迟扩展!读取该变量的实际值。

方法二:使用CALL二次解析(无需延迟扩展)

如果场景中无法使用延迟扩展,可以借助call命令的二次变量解析特性:

@echo off

setlocal

set array1[1]=1
set array1[2]=2

set array2[1]=3
set array2[2]=4

call :whatever array1
call :whatever array2

goto :eof

:whatever
call echo value of first array element is %%%1[1]%%
call echo value of second array element is %%%1[2]%%
goto :eof

关键说明:

  • %%%1[1]%%会被首次解析为%array1[1]%,随后call命令会二次解析这个变量,最终得到对应元素的值。

两种方法运行后都能得到你预期的输出:

value of first array element is 1
value of second array element is 2
value of first array element is 3
value of second array element is 4

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 20:03:12