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

查看:167
本文介绍了算上数组的长度,返回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[]


  • 使用数组SUBEX pression语法:

  • 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天全站免登陆