The PowerShell Array Removal

  • Comments posted to this topic are about the item The PowerShell Array Removal

  • 9 is the correct answer (shame on me), but there is a subtlety here with PowerShell arrays. Setting $numbers[4] = $null does not change the size of the array, only the value stored at index 4. $numbers.length and $numbers.count still return 10. A simple loop over the elements also shows that it's still there.

    foreach ($elem in $numbers) { Write-Host $elem }
    1
    2
    3
    4

    6
    7
    8
    9
    10

     

  • I don't get it. If you set element 4 to Null, why is it that number 5 vanishes from the array?

  • PowerShell arrays are 0-based. We have 10 elements, so the index goes from 0 to 9. The assignment was $numbers = @(1,2,3,4,5,6,7,8,9,10). So $numbers[0] = 1, $numbers[1] = 2, ..., $numbers[4] = 5, ..., $numbers[9] = 10.

  • It was a weird thing I stumbled on when working with arrays and removing elements as dale_berta noted, the array is still the same size, which is expected. It shouldn't actually remove the item from memory, but change the value. What's weird is that the display doesn't show it, which I think would be confusing to many users.

    If I were to set an array element in python to None, it's still there if I just pick the array. In C, the memory location is still there and I either copy the array or move elements to fill a hole, depending on what I want to do.

    I think this is a poor implementation choice in PoSh.

  • dale_berta wrote:

    PowerShell arrays are 0-based. We have 10 elements, so the index goes from 0 to 9. The assignment was $numbers = @(1,2,3,4,5,6,7,8,9,10). So $numbers[0] = 1, $numbers[1] = 2, ..., $numbers[4] = 5, ..., $numbers[9] = 10.

    DOH! All the years I've been programming and that didn't occur to me. SMH - thanks.

  • This was removed by the editor as SPAM

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply