Count length of array and return 1 if it only contains one element

前端 未结 4 1820
轻奢々
轻奢々 2020-12-09 15:33
$cars = \"bmw\",\"audi\",\"volvo\",\"vw\"
echo $cars.length

returns 4, but

$cars = \"bmw\"

returns 3 because it

相关标签:
4条回答
  • 2020-12-09 16:01

    declare you array as:

    $car = array("bmw")
    

    EDIT

    now with powershell syntax:)

    $car = [array]"bmw"
    
    0 讨论(0)
  • 2020-12-09 16:11

    Instead of writing echo $cars.length write echo @($cars).length

    0 讨论(0)
  • 2020-12-09 16:14

    A couple other options:

    1. Use the comma operator to create an array:

      $cars = ,"bmw"
      $cars.GetType().FullName
      # Outputs: System.Object[]
      
    2. Use array subexpression syntax:

      $cars = @("bmw")
      $cars.GetType().FullName
      # Outputs: System.Object[]
      

    If you don't want an object array you can downcast to the type you want e.g. a string array.

     [string[]] $cars = ,"bmw"
     [string[]] $cars = @("bmw")
    
    0 讨论(0)
  • 2020-12-09 16:26

    Maybe I am missing something (lots of many-upvotes-members answers here that seem to be looking at this different to I, which would seem implausible that I am correct), but length is not the correct terminology for counting something. Length is usually used to obtain what you are getting, and not what you are wanting.

    $cars.count should give you what you seem to be looking for.

    0 讨论(0)
提交回复
热议问题