Why is a leading comma required when creating an array?

前端 未结 3 864
死守一世寂寞
死守一世寂寞 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:43

    Powershell uses both a comma and a line break as an array separator. Your first declare:

    $files1 = @(
    @(4, 1024)
    , @((7), (16))
    )
    

    Creates the following:

    $files1[0] = 4
    $files1[1] = 1024
    $files1[2] = @(7,16)
    

    Your second declare

    $files1 = @(
    , @(4, 1024)
    , @((7), (16))
    )
    

    Creates the following:

    $files1[0] = @(4, 1024)
    $files1[1] = @(7, 16)
    

    As to the parsing decision, it is dependent on the first non-white space character encountered on a line: Array Literals In PowerShell and Understanding PowerShell Parsing Modes

提交回复
热议问题