【发布时间】:2022-03-23 03:00:04
【问题描述】:
如何获取数组元素从第一个到倒数第二个的范围?
例如,
$array = 1,2,3,4,5
$array[0] - will give me the first (1)
$array[-2] - will give me the second last (4)
$array[0..2] - will give me first to third (1,2,3)
$array[0..-2] - I'm expecting to get first to second last (1,2,3,4) but I get 1,5,4 ???
我知道我可以做长手并转到for($x=0;$x -lt $array.count;$x++),但我正在寻找方括号快捷方式。
【问题讨论】:
-
你可以这样做
$array[0..($array.length-2)]。 -
不幸的是,罗伯特的建议是我所知道的最好的方法。我也希望 $array[0..-2] 能够按照您的预期行事。但是不,它向后索引 0 -> [len-1] -> [len-2]。我真的不明白这有什么用。
-
@robert.westerlund 您应该添加您的评论作为答案,以便我们可以关闭此问题:)
标签: arrays powershell