批处理 - 数组

• 需要使用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命令专门定义数组的每个元素。

• 带有/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%```

`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```

相关推荐

Vim 实用技巧必知必会 -〔吴咏炜 - 〕

视频推荐

D01_01掌握批处理文件的创建与编辑方法