gpt4 book ai didi

powershell - PS : Get index in an array list

转载 作者:行者123 更新时间:2023-12-02 23:42:08 25 4
gpt4 key购买 nike

我有一个字符串数组。不确定是否有简单的方法来获取数组中第一个找到的项目的索引?

# example array
$array = "A", "B", "C"
$item = "B"
# the following line gets null, any way to get its index?
$index = $array | where {$_ -eq $item} | ForEach-Object { $_.Index }

我可以循环执行它。不确定是否有其他方法?

最佳答案

如果您知道该值在数组中只出现一次,那么 [array]::IndexOf() 方法是一个很好的方法:

$array = 'A','B','C'
$item = 'B'
$ndx = [array]::IndexOf($array, $item)

除了简洁明了之外,如果数组非常大,这种方法的性能比使用像Where-Object这样的PowerShell cmdlet要好得多。尽管如此,它只会找到指定项目的第一次出现。但是您可以使用 IndexOf 的其他重载来查找下一个匹配项:

$ndx = [array]::IndexOf($array, $item, $ndx+1)

如果未找到该项目,$ndx 将为 -1。

关于powershell - PS : Get index in an array list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1948107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com