如何在 PowerShell 中按索引删除数组元素
最近,我需要在 PowerShell 中按索引删除数组元素。在本 PowerShell 教程中,我将解释在 PowerShell 中按索引删除数组元素的不同方法。
要在 PowerShell 中按索引删除元素,可以使用数组切片方法创建一个不包含该元素的新数组。例如, $newArray=$array[0..($indexToRemove-1)] + $array[($indexToRemove+1)..($array.Length-1)] 将删除 $indexToRemove 处的元素。或者,您可以使用 ArrayList 及其 RemoveAt 方法来实现更直接的方法:$arrayList.RemoveAt($indexToRemove)。这两种方法都可以有效地从数组中指定索引处删除元素。
在 PowerShell 中按索引删除数组元素
数组是可以通过数字索引访问的项目的集合。在 PowerShell 中,数组的大小是固定的,这意味着一旦定义了数组,就无法直接增加或减少其大小。
现在,让我们看看在 PowerShell 中按索引删除数组元素的不同方法。
方法 1:创建一个不包含该元素的新数组
通过索引从数组中删除元素的一种方法是创建一个新数组,在 PowerShell 中排除指定索引处的元素。这是一个例子:
# Original array
$array = 1, 2, 3, 4, 5
# Index to remove
$indexToRemove = 2
# Create a new array excluding the index
$newArray = $array[0..($indexToRemove-1)] + $array[($indexToRemove+1)..($array.Length-1)]
# Display the new array
$newArray
此方法使用数组切片创建两个子数组:一个位于要删除的索引之前,一个位于要删除的索引之后。然后将它们连接起来形成新的数组,其中不含不需要的元素。
您可以在下面的屏幕截图中看到输出:
方法2:使用ArrayList
由于标准 PowerShell 数组的大小是不可变的,因此如果您想直接按索引删除项目,可以使用 PowerShell ArrayList。 ArrayList 是一个动态数组,这意味着它可以根据需要增长和缩小。使用方法如下:
# Create an ArrayList
$arrayList = New-Object System.Collections.ArrayList
$arrayList.AddRange(@(1, 2, 3, 4, 5))
# Index to remove
$indexToRemove = 2
# Remove the element at the index
$arrayList.RemoveAt($indexToRemove)
# Display the ArrayList
$arrayList这里使用 RemoveAt 方法直接从 ArrayList 中删除指定索引处的项目。
方法 3:使用Where-Object Cmdlet
在 PowerShell 中按索引删除元素的另一种方法涉及使用 Where-Object cmdlet。此 cmdlet 允许您过滤掉所需索引处的元素:
# Original array
$array = 1, 2, 3, 4, 5
# Index to remove
$indexToRemove = 2
# Remove the element at the index using Where-Object
$newArray = $array | Where-Object { $_ -ne $array[$indexToRemove] }
# Display the new array
$newArray此方法将数组中的每个项目 ($_) 与要删除的索引处的项目进行比较,从而有效地将其过滤掉。
当我使用 VS code 执行上述代码后,您可以在下面的屏幕截图中看到输出:
方法 4:将 ForEach-Object 与条件结合使用
在 PowerShell 中按索引从数组中删除元素的另一种方法是使用带有条件语句的 ForEach-Object。这是一个例子:
# Original array
$array = 1, 2, 3, 4, 5
# Index to remove
$indexToRemove = 2
# Initialize an empty array for the result
$newArray = @()
# Loop through the original array and exclude the index to remove
$array | ForEach-Object {
if ($array.IndexOf($_) -ne $indexToRemove) {
$newArray += $_
}
}
# Display the new array
$newArray
此方法迭代原始数组中的每个元素并将其添加到新数组中,除非它位于要删除的索引处。
查看下面的屏幕截图以供参考:
注意:通过索引删除元素时,请记住,如果从数组中间删除一个元素,后续元素的索引将会更改。如果您要删除循环中的元素,这可能会出现问题。始终做好相应的计划,以避免出现意外结果。
结论
在 PowerShell 中通过索引从数组中删除元素可以通过多种方法实现,例如使用 ArrayList、使用Where-Object 进行过滤或使用ForEach-进行迭代对象等
在本 PowerShell 教程中,我解释了如何使用各种方法在 PowerShell 中按索引删除数组元素。


