我正在处理批处理文件。我有一个数组:
setlocal enabledelayedexpansion
set Base_list[0]=Base1
set Base_list[1]=Base2
set Base_list[2]=Base3
set Base_list[3]=Base4
set Base_list[4]=Base5
set Base_list[5]=Base6
set Current_Node=Node1
if "%Current_Node%" == "Node1" ( for /l %%a in (0 ,%counter% , %Base_list%) do (
// do some stuff
)
)
如何打印名为Base_list
的数组?
如何遍历此数组?
答案 0 :(得分:0)
我想,for /L
让你完全糊涂了。
正确的语法为for /L %%i in (<start>,<step>,<end>) do...
@echo off
setlocal enabledelayedexpansion
set Base_list[0]=Base1
set Base_list[1]=Base2
set Base_list[2]=Base3
set Base_list[3]=Base4
set Base_list[4]=Base5
set Base_list[5]=Base6
set Current_Node=Node1
REM list array:
set base_list[
REM list values only:
for /f "tokens=2 delims==" %%i in ('set Base_list[') do echo %%i
REM get size of the array:
for /f %%i in ('set base_list[ ^|find /c "="') do set count=%%i
echo size is %count%
REM subtract one because array starts with 0:
set /a count-=1
if "%Current_Node%" == "Node1" for /l %%a in (0,1,%count%) do (
echo %%a: some stuff with !base_list[%%a]!
)
答案 1 :(得分:0)
打印:
set base_list[
(假设您不希望保留数字序列,如果索引&gt; 9并且没有名称以base_list[
开头的不需要的变量 - 您没有指定)
迭代:
for /f "tokens=1*delims==" %%a in ('set base_list[ 2^>nul') do echo %%b
或
for /f "tokens=1*delims==" %%a in ('set base_list[ 2^>nul') do echo %%a has value %%b
取决于你想要做什么 - 与&#34; print&#34;。
相同的条件答案 2 :(得分:0)
您的代码中有一些小错误:
这是您的代码的正确版本:
@echo off
setlocal enabledelayedexpansion
set Base_list[0]=Base1
set Base_list[1]=Base2
set Base_list[2]=Base3
set Base_list[3]=Base4
set Base_list[4]=Base5
set Base_list[5]=Base6
set Current_Node=Node1
rem Explicitly set the counter:
set counter=5
if "%Current_Node%" == "Node1" (
for /l %%a in (0 , 1, %counter%) do (
rem do some stuff
echo Element %%a in Base_list array is: !Base_list[%%a]!
)
)
但是,这段代码可以用更简单的方式编写:
@echo off
setlocal enabledelayedexpansion
rem Create the array via elements placed in a FOR command
rem at same time, generate the counter:
set counter=0
for %%a in (Base1 Base2 Base3 Base4 Base5 Base6) do (
set Base_list[!counter!]=%%a
set /A counter+=1
)
rem Adjust the counter because the array is zero-based:
set /A counter-=1
set Current_Node=Node1
if "%Current_Node%" == "Node1" (
for /l %%a in (0 , 1, %counter%) do (
rem do some stuff
echo Element %%a in Base_list array is: !Base_list[%%a]!
)
)
我建议您阅读批处理文件中有关阵列管理的this post。