What is the idiomatic way to slice an array relative to both of its ends?

前端 未结 7 1433
梦如初夏
梦如初夏 2021-02-06 20:35

Powershell\'s array notation has rather bizarre, albeit documented, behavior for slicing the end of arrays. This section from the official documentation sums up the bizarreness

7条回答
  •  南方客
    南方客 (楼主)
    2021-02-06 21:09

    This could be the most idiomatic way to slice an array with both of its ends:

    $array[start..stop] where stop is defined by taking the length of the array minus a value to offset from the end of the array:

    $a = 1,2,3,4,5,6,7,8,9
    $start = 2
    $stop = $a.Length-3
    $a[$start..$stop]
    

    This will return 3 4 5 6 7

    The start value starts counting with zero, so a start value of '2' gives you the third element of the array. The stop value is calculated with ($a.Length-3), this will drop the last two values because $a.Length-3 itself is included in the slice.

    I have defined $start and $stop for clarity, obviously you can also write it like this:

    $a = 1,2,3,4,5,6,7,8,9
    $a[2..($a.Length-3)]
    

    This will also return 3 4 5 6 7

提交回复
热议问题