在无效数组中获取第一个对象

发布于 2025-02-13 22:52:37 字数 374 浏览 2 评论 0 原文

我有一个类似的数组:

episodes?: Episode[];

在一个函数中,我想在该数组中获取第一个对象。我尝试了以下内容:

let episode: Episode = this.episodes?[0];

var episode = this.episodes?[0];

两者都会给出以下错误:

错误:src/app/pissodes/pissodes.component.ts:30:45-错误ts1005:':'预期。

如何从此数组中获取项目?

I have an array like this:

episodes?: Episode[];

In a function I want to get the first object in that array. I have tried the following:

let episode: Episode = this.episodes?[0];

or

var episode = this.episodes?[0];

However these both gives the following error:

Error: src/app/episodes/episodes.component.ts:30:45 - error TS1005: ':' expected.

How do I get an item from this array?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

热风软妹 2025-02-20 22:52:37

您需要

this.episodes?.[0];

请参见Playground


但是,您仍然有一个类型错误:

let episode: Episode = this.episodes?.[0];

这是因为右侧的结果可能是 undefined 。如何处理这取决于您。但是,您需要以某种方式处理类型是情节|的事实。未定义

例如,您必须测试值首先存在:

let episode = this.episodes?.[0];
if (episode) {
  console.log(episode.season) // works
} else {
  throw new Error("one episode is required!")
}

请参阅操场

You need a .

this.episodes?.[0];

See playground


However, you'll still have a type error in:

let episode: Episode = this.episodes?.[0];

This is because the result of the right side might be undefined. How to handle that is up to you. But somehow you'll need to handle the fact that the type is Episode | undefined.

For example, you'd have to test the value to see if it exists first:

let episode = this.episodes?.[0];
if (episode) {
  console.log(episode.season) // works
} else {
  throw new Error("one episode is required!")
}

See playground

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文