文章内容

2023/11/20 1:39:13,作 者: 黄兵

ts 判断数组是否为空

在 TypeScript 中,您可以使用以下方法来判断数组是否为空:

  1. 使用数组的 length 属性:
const arr: number[] = [];

if (arr.length === 0) {
  console.log("数组为空");
} else {
  console.log("数组不为空");
}
  1. 使用 Array.isArray() 方法:
const arr: number[] = [];

if (Array.isArray(arr) && arr.length === 0) {
  console.log("数组为空");
} else {
  console.log("数组不为空");
}

其中,Array.isArray() 方法用于检查一个变量是否是数组,返回值为 true 或 false。因此,我们在判断数组是否为空时需要先使用 Array.isArray() 方法来确保变量确实是一个数组。


其它相关推荐:

1、[TypeScript] Unresolved basetypes

2、TypeScript 和 JavaScript 的区别

3、Typescript默认值以及可选参数

4、您的项目文件使用的 TypeScript 编译器和工具的版本不同于此机器上当前安装的版本

5、Error: StaticInjectorError(AppModule)[VerifyEmailComponent -> AccountService]:

分享到:

发表评论

评论列表