PS:在数组列表中获取索引

Dav*_*.ca 8 powershell

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

# 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 }
Run Code Online (Sandbox Code Playgroud)

我可以循环完成.不确定是否有其他方法?

Kei*_*ill 26

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

$array = 'A','B','C'
$item = 'B'
$ndx = [array]::IndexOf($array, $item)
Run Code Online (Sandbox Code Playgroud)

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

$ndx = [array]::IndexOf($array, $item, $ndx+1)
Run Code Online (Sandbox Code Playgroud)

如果找不到该项,$ ndx将为-1.


Pet*_*ale 11

使用for循环(或循环遍历数组索引的foreach循环......相同的差异).我不知道在foreach循环中保存当前数组索引的任何系统变量,我认为不存在.

# example array
$array = "A", "B", "C"
$item = "B"
0..($array.Count - 1) | Where { $array[$_] -eq $item }
Run Code Online (Sandbox Code Playgroud)