批处理数组

数组类型并没有明确定义为批处理脚本中的类型,但可以实现。 在批处理脚本中实现数组时需要注意以下几点。

  • 数组中的每个元素都需要用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


访问数组

可以使用下标语法从数组中检索值,并在数组的名称后面立即传递要检索的值的索引。

示例

@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

上一篇:批处理字符串

下一篇:批处理决策结构

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程