# 批處理數組

• 數組中的每個元素都需要用`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[0]=comments
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``````
0 條評論，你可以發表評論，我們會進行改進