如何创建可以批量编辑的数组?

时间:2018-11-08 17:34:51

标签: arrays list batch-file arraylist

我最近承担了一个项目,以在Windows上批量学习脚本。

我想编写一个代码,使我能够创建一个可以打印,添加和删除的数组。

在我的脑海中,我会看到类似的东西:

set List = [Bob, Adam, Steve] ::Creates an array
echo What is your name?
set /p name= 
list.add(List + name) ::Adds name to list
echo Hello List[3] ::Prints the 4th name in array
echo My name is List[0] ::Prints the 1st name in array

那只是一个粗略的草图,我知道它是行不通的,但是我在正确的路线上吗?如果是这样,需要更改什么?

2 个答案:

答案 0 :(得分:1)

那不是数组,那是一个列表(种类; Batch只知道一种类型的变量:字符串)。这是您的伪代码的语法正确版本:

set "List=Bob,Adam,Steve" 
set /p "name=What is your name? "   
set "list=%list%,%name%"
for /f "tokens=4 delims=," %%a in ("%list%") do echo Hello %%a
for /f "tokens=1 delims=," %%a in ("%list%") do echo My name is %%a

为了您的兴趣:有一篇关于Arrays, linked lists and other data structures in cmd.exe (batch) script的详细文章

EDIT
对于您的“在for /l循环内”的问题:for对于tokens部分的参数有些挑剔,但是可以使用call解决:

@echo off
set "List=Bob,Adam,Steve" 
set amount=3 
for /l %%i in (%amount%; -1; 1) do call :sub %%i
goto :eof

:sub
for /f "tokens=%1 delims=," %%a in ("%list%") do echo Hello %%a 
goto :eof

答案 1 :(得分:1)

这是一个替代示例:

@Echo Off
SetLocal EnableDelayedExpansion
Set "#=0"
Set "List=Bob,Adam,Steve"
Set /P "name=What is your name? "
Set "List=%List%,%name%"
Set "List[!#!]=%List:,="&Set/A #+=1&Set "List[!#!]=%"
Rem Show all pseudo array items
Set List[
Rem Prints the 4th name in pseudo array
Echo My name is %List[4]%
Rem Prints the 1st name in pseudo array
Echo My name is %List[0]%
Pause