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

前端 未结 7 1429
梦如初夏
梦如初夏 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:27

    If you are looking for, say, the first three and last three elements in an array, with the results in an array, a little array addition will take care of the need.

    [array]$A = (([int][char]'A')..([int][char]'Z')) | ForEach-Object {[char]$_}
    $B = $A[0..2]+$A[-3..-1]
    Clear-Host
    Write-Host "Original List"
    Write-Host $A -NoNewline -Separator ', '
    Write-Host
    Write-Host "First three and last three"
    Write-Host $B -NoNewline -Separator ', '
    

    Yields:

    Original List
    A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z
    First three and last three
    A, B, C, X, Y, Z
    

提交回复
热议问题