你在你的代碼中的幾個小錯誤:
- 您還沒有初始化的計數器變量。
- 的FOR命令是略有不同的格式
- 註釋通過REM命令插入,而不是//
這是你的代碼的正確版本:
@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批處理文件中的數組管理。