【问题标题】:How to create a function in typescript which takes array as an user input and how to find array length?如何在打字稿中创建一个将数组作为用户输入的函数以及如何查找数组长度?
【发布时间】:2022-01-04 06:54:52
【问题描述】:

我需要在 typescript 中创建一个函数,该函数将数组作为接受任何类型数组的输入。然后计算其中存在的元素数量并返回。

我想要一个类似的输出 让如果用户输入:[“板球”,“足球”] 然后输出:2

如何使用打字稿解决这个问题?

【问题讨论】:

标签: javascript arrays function input types


【解决方案1】:

你可以使用泛型类型 T 来允许参数中的任何类型的数组

arrayLength<T>(myArray:T[]): number {
    return myArray.length;
}

【讨论】:

    【解决方案2】:

    您可以查看本教程,了解如何将数组传递给函数:>> https://www.tutorialspoint.com/typescript/typescript_passing_arrays_to_functions.htm

    要计算一个数组的长度,它会是这样的:

    console.log(array.length);
    

    详细文档:>> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-26
      • 2015-06-29
      • 2014-01-18
      • 1970-01-01
      • 2023-03-13
      • 2021-03-11
      • 2020-07-29
      • 2020-09-28
      相关资源
      最近更新 更多