我已经为bat文件编写了一个脚本,它将打印列表中的随机值。 但是我使用它的索引来访问列表值时遇到问题
我的代码是:
set list=A B C D a b c
echo %list[3]%
for /l %%a in (1,1,6) do (
@set /a bottomlimit = 0
@set /a upperlimit = 5
@set /a num = !bottomlimit! + !RANDOM! %% !upperlimit! - !bottomlimit! + 1
echo %list[!num!]%
TIMEOUT /T 5
)
等待您的宝贵解决方案。
答案 0 :(得分:1)
@echo off
setlocal EnableDelayedExpansion
set list=A B C D a b c
set /a counter=1
for %%a in (%list%) do (
set "list[!counter!]=%%~a"
set /a counter=counter+1
)
set list[
for /l %%a in (1,1,6) do (
@set /a bottomlimit = 0
@set /a upperlimit = 5
@set /a num = bottomlimit + !RANDOM! %% upperlimit - bottomlimit + 1
for %%# in (!num!) do echo !list[%%#]!
TIMEOUT /T 5
)
endlocal
答案 1 :(得分:1)
只有三种选择。第一,处理你的方法。环境变量中“纯”数组的第二个。第三个将混合两个,如选项1中的列表定义,但迭代列表以在选项2中生成数组。
@echo off
setlocal enableextensions enabledelayedexpansion
REM OPTION 1 - The list
echo -------------------------------------------------
setlocal
set "list=A B C D a b c"
set /a bottomlimit=0
set /a upperlimit=6
for /l %%a in (1,1,6) do (
set /a "num=!bottomlimit! + ( !RANDOM! %% (!upperlimit! - !bottomlimit! + 1))"
set "pos=0"
for %%l in (!list!) do if defined pos if !pos!==!num! ( echo %%l & set "pos=" ) else ( set /a "pos+=1")
)
endlocal
REM OPTION 2 - The "pure" array
echo -------------------------------------------------
setlocal
set "list[0]=A"
set "list[1]=B"
set "list[2]=C"
set "list[3]=D"
set "list[4]=a"
set "list[5]=b"
set "list[6]=c"
set /a bottomlimit=0
set /a upperlimit=6
for /l %%a in (1,1,6) do (
set /a "num=!bottomlimit! + ( !RANDOM! %% (!upperlimit! - !bottomlimit! + 1))"
for %%n in (!num!) do echo !list[%%n]!
)
endlocal
REM OPTION 3 - The remix
echo -------------------------------------------------
setlocal
set "list=A B C D a b c"
set "pos=0"
for %%l in (!list!) do ( set "list[!pos!]=%%l" & set /a "pos+=1" )
set /a "bottomlimit=0"
set /a "upperlimit=!pos!-1"
for /l %%a in (1,1,6) do (
set /a "num=!bottomlimit! + ( !RANDOM! %% (!upperlimit! - !bottomlimit! + 1))"
for %%n in (!num!) do echo !list[%%n]!
)
endlocal
endlocal
exit /b
答案 2 :(得分:0)
您可以使用echo/%list:~3,1%
,但不能使用echo/%list:~%num%,1%
试试这个:
@echo off
set "list=ABCDabc"
echo/%list:~3,1%
set /a bottomlimit = 0
set /a upperlimit = 5
for /l %%a in (1,1,6) do (
CALL:CALC
CALL _temp.bat
Timeout /t 5
)
del _temp.bat
pause >nul
exit/b
:CALC
set /a num = %bottomlimit% + %random% %% %upperlimit% - %bottomlimit% + 1
echo/set "list=%list%">_temp.bat
echo/echo/%%list:~%num%,1%%>>_temp.bat
exit/b