代码之家  ›  专栏  ›  技术社区  ›  Eric Schoonover thSoft

当仅存在一个元素时,交错PowerShell数组正在丢失维度

  •  8
  • Eric Schoonover thSoft  · 技术社区  · 15 年前

    我有以下PowerShell函数,它适用于除 1 . 如果我给它一个 1. 它将返回一个包含两个元素的数组 1,1 而不是单个元素本身是两个元素的数组 (1,1) .

    有没有办法让PowerShell返回一个锯齿状数组,其中一个元素本身就是数组?

    function getFactorPairs {
        param($n)
        $factorPairs = @()
        $maxDiv = [math]::sqrt($n)
        write-verbose "Max Divisor: $maxDiv"
        for($c = 1; $c -le $maxDiv; $c ++) {
            $o = $n / $c;
            if($o -eq [math]::floor($o)) {
                write-debug "Factor Pair: $c, $o"
                $factorPairs += ,@($c,$o) # comma tells powershell to add defined array as element in existing array instead of adding array elements to existing array
            }
        }
        return $factorPairs
    }
    

    ~» (getFactorPairs 1).length  
       DEBUG: Factor Pair: 1, 1  
       2  
    
    ~» (getFactorPairs 6).length  
       DEBUG: Factor Pair: 1, 6  
       DEBUG: Factor Pair: 2, 3  
       2  
    
    2 回复  |  直到 15 年前
        1
  •  13
  •   Tim Danner    12 年前

    我在Windows XP上的PowerShell V2 CTP上测试了这一点,并看到了与OP相同的结果。

    return ,$factorPairs
    

    见基思·希尔的博客 Effective PowerShell Item 8: Output Cardinality - Scalars, Collections and Empty Sets - Oh My! 想了解更多细节。

        2
  •  5
  •   Keith Hill    15 年前

    你很接近。您遇到的问题是,当从函数返回阵列时,PowerShell会展开(展平)阵列。使用逗号运算符按原样返回数组而不展开它:

    return ,$factorPairs