I've mentioned constant index in the title because all question in StackOverflow related to array indexing in a batch file were focused on accessing array using variable index inside a loop.
我是批处理脚本的新手。如果数组被初始化为列表(在一行中)而不是每个元素被单独初始化,我想打印具有常量索引的数组值。我写了一个片段,其中我可以打印 arr
但不是 list
的值。
@echo off
set arr[0]=1
set arr[1]=2
set arr[2]=3
set list=1 2 3 4
REM Result is 2
echo %arr[1]%
REM Won't print
echo %list[1]%
最佳答案
字符串中的列表不是数组,this answer 2 天前展示了如何将字符串列表转换为数组。
要使数组索引基于零,请使用此更改后的版本
:: SO_51225079.cmd
@echo off & Setlocal EnableDelayedExpansion
set arr[0]=1
set arr[1]=2
set arr[2]=3
set i=-1&set "list= 1 2 3 4"
Set "list=%list: ="&Set /a i+=1&Set "list[!i!]=%"
set list
REM Result is 2
echo %arr[1]%
REM Won't print
echo %list[1]%
示例输出:
> SO_51225079.cmd
list[0]=1
list[1]=2
list[2]=3
list[3]=4
2
2
关于arrays - 访问批处理文件中常量索引处的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51225079/