# 批次處理陣列

• 陣列中的每個元素都需要用`set`命令來定義。
• `for`迴圈將需要遍歷陣列的值。

## 建立一個陣列

``````set a[0]=1
``````

``````@echo off
set list=1 2 3 4
(for %%a in (%list%) do (
echo %%a
))
``````

``````1
2
3
4
``````

## 存取陣列

``````@echo off
set a[0]=1
echo %a[0]%
``````

``````@echo off
set a[0]=1
set a[1]=2
set a[2]=3
echo The first element of the array is %a[0]%
echo The second element of the array is %a[1]%
echo The third element of the array is %a[2]%
``````

``````The first element of the array is 1
The second element of the array is 2
The third element of the array is 3
``````

## 修改陣列

``````@echo off
set a[0]=1
set a[1]=2
set a[2]=3
Rem Adding an element at the end of an array
Set a[3]=4
echo The last element of the array is %a[3]%
``````

``````The last element of the array is 4
``````

``````@echo off
set a[0]=1
set a[1]=2
set a[2]=3
Rem Setting the new value for the second element of the array
Set a[1]=5
echo The new value of the second element of the array is %a[1]%
``````

``````The new value of the second element of the array is 5
``````

## 疊代陣列

``````@echo off
setlocal enabledelayedexpansion
set topic[1]=variables
set topic[2]=Arrays
set topic[3]=Decision making
set topic[4]=Time and date
set topic[5]=Operators

for /l %%n in (0,1,5) do (
echo !topic[%%n]!
)
``````

• 陣列中的每個元素都需要使用`set`命令專門定義。
• `for`迴圈移動範圍的`/L`引數用於迭代陣列。

``````Comments
variables
Arrays
Decision making
Time and date
Operators
``````

## 陣列的長度

``````@echo off
set Arr[0]=1
set Arr[1]=2
set Arr[2]=3
set Arr[3]=4
set "x=0"
:SymLoop

if defined Arr[%x%] (
call echo %%Arr[%x%]%%
set /a "x+=1"
GOTO :SymLoop
)
echo "The length of the array is" %x%
``````

``````The length of the array is 4
``````

## 在陣列中建立結構

``````@echo off
set len=3
set obj[0].Name=Joe
set obj[0].ID=1
set obj[1].Name=Mark
set obj[1].ID=2
set obj[2].Name=Mohan
set obj[2].ID=3
set i=0
:loop

if %i% equ %len% goto :eof
set cur.Name=
set cur.ID=

for /f "usebackq delims==.tokens=1-3" %%j in (`set obj[%i%]`) do (
set cur.%%k=%%l
)
echo Name=%cur.Name%
echo Value=%cur.ID%
set /a i=%i%+1
goto loop
``````

• 使用`set`命令定義的每個變數具有與陣列的每個索引關聯的`2`個值。
• 變數`i`設定為`0`，以便可以遍歷結構將陣列的長度為`3`
• 總是檢查`i`的值是否等於`len`的值，如果不是，則迴圈遍歷程式碼。
• 可以使用`obj[%i%]`表示法存取結構的每個元素。

``````Name=Joe
Value=1
Name=Mark
Value=2
Name=Mohan
Value=3
``````