批處理指令碼 - 陣列



批處理指令碼中沒有專門定義陣列型別,但可以實現。在批處理指令碼中實現陣列時,需要注意以下幾點。

  • 陣列的每個元素都需要使用 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 命令專門定義。

  • 使用帶 /L 引數的 'for' 迴圈遍歷範圍來遍歷陣列。

輸出

以上命令產生以下輸出。

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%

輸出

輸出以上命令產生以下輸出。

1
2
3
4
"The length of the array is" 4

在陣列中建立結構

結構也可以在批處理檔案中實現,只需進行一些額外的編碼即可實現。以下示例演示瞭如何實現。

示例

@echo off 
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 
FOR /L %%i IN (0 1 2) DO  (
   call echo Name = %%obj[%%i].Name%%
   call echo Value = %%obj[%%i].ID%%
)

關於以上程式碼,需要注意以下關鍵事項。

  • 使用 set 命令定義的每個變數都與陣列的每個索引關聯了 2 個值。

  • 變數 i 設定為 0,以便我們可以迴圈遍歷結構,其長度為 3。

  • 我們始終檢查 i 的值是否等於 len 的值,如果不是,則迴圈遍歷程式碼。

  • 我們可以使用 obj[%i%] 表示法訪問結構的每個元素。

輸出

以上命令產生以下輸出。

Name=Joe 
Value=1 
Name=Mark 
Value=2 
Name=Mohan 
Value=3
廣告