批處理數組

數組類型並沒有明確定義為批處理腳本中的類型,但可以實現。 在批處理腳本中實現數組時需要注意以下幾點。

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

創建一個數組

一個數組是通過使用下麵的set命令創建的。

set a[0]=1

其中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]%

在這個例子中,索引從0開始,第一個元素可以使用索引訪問為0,第二個元素可以使用索引訪問為1,依此類推。通過下麵的例子來看看如何創建,初始化和訪問數組 -

@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

修改數組

要將一個元素添加到數組的末尾,可以使用set元素以及數組元素的最後一個索引。

示例

@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

迭代數組

遍歷數組是通過使用for迴圈並遍歷數組的每個元素來實現的。以下示例顯示了一個可以實現數組的簡單方法。

@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

上一篇: 批處理字串 下一篇: 批處理決策結構