计算数组的长度,如果只包含一个元素则返回1 [英] Count length of array and return 1 if it only contains one element

查看:28
本文介绍了计算数组的长度,如果只包含一个元素则返回1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$cars = "bmw","audi","volvo","vw"
echo $cars.length

返回 4,但是

$cars = "bmw"

返回 3 因为它计算字符数..

returns 3 because it counts the characters..

如果数组只包含一个项目,有没有办法返回 1?

Is there a way I can return 1 if the array only contains one item?

推荐答案

其他几个选项:

  1. 使用逗号运算符创建数组:

  1. Use the comma operator to create an array:

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

  • 使用数组子表达式语法:

  • 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")
    

    这篇关于计算数组的长度,如果只包含一个元素则返回1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆