Why is a leading comma required when creating an array?

前端 未结 3 862
死守一世寂寞
死守一世寂寞 2021-01-11 23:00

I want to create an array containing arrays of two numbers. Pretty straightforward. However, If I do not provide a leading comma before the first array, it is incorrect. Why

3条回答
  •  情话喂你
    2021-01-11 23:33

    The key to understanding the Array subexpression operator @( ) is the realization that you don't need it to create arrays, instead arrays are created with the Comma operator ,

    As a binary operator, the comma creates an array. As a unary operator, the comma creates an array with one member. Place the comma before the member.

    $myArray = 1,2,3
    $SingleArray = ,1
    
    $xs = (1,2,3), (4,5,6)       # Count: 2    
    $ys = (1,2,3),
    (4,5,6)                      # Count: 2
    

    Now consider

    # A - two expressions, each expression yields one array of size 3
    (1,2,3)
    (4,5,6)
    
    # B - one expression resulting in an array of two elements
    (1,2,3),
    (4,5,6)
    
    # C - similar to A except the sizes are 3 and 1 
    #     (the second array contains a single element)
    (1,2,3)
    ,(4,5,6)
    

    And the final step is to realize that

    in essence, the @(...) operation is syntactic sugar for [array] $(...)

    as explained by the PowerShell Team Blog (The link was given by Christopher G. Lewis answer). Although the meaning and limitations of in essence is not entirely clear to me.

提交回复
热议问题