December 22, 2023 at 12:00 am
Comments posted to this topic are about the item The PowerShell Array Removal
December 22, 2023 at 2:21 pm
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
December 22, 2023 at 3:31 pm
I don't get it. If you set element 4 to Null, why is it that number 5 vanishes from the array?
December 22, 2023 at 3:59 pm
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.
December 22, 2023 at 5:15 pm
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.
December 23, 2023 at 1:42 pm
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.
December 24, 2023 at 9:07 am
This was removed by the editor as SPAM
April 5, 2024 at 9:00 am
saying an array is '0' based does not really illustrate the situation. The index is a position offset. So the first element is at the allocated address and the second element is offset by 1 position and the third by 2 positions etc.
At the end of most articles is a small blurb called a person's signature which exists to provide information about how to get in touch with the person posting, including their email address, phone number, address, or where they're located. Signatures have become the graffiti of computers. People put song lyrics, pictures, philosophical quotes, even advertisements in them. (Note, however, that advertising in your signature will more often than provoke negative responses until you take it out.)
Viewing 8 posts - 1 through 7 (of 7 total)
You must be logged in to reply to this topic. Login to reply