在无效数组中获取第一个对象
我有一个类似的数组:
episodes?: Episode[];
在一个函数中,我想在该数组中获取第一个对象。我尝试了以下内容:
let episode: Episode = this.episodes?[0];
或
var episode = this.episodes?[0];
两者都会给出以下错误:
错误:src/app/pissodes/pissodes.component.ts:30:45-错误ts1005:':'预期。
如何从此数组中获取项目?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要
。
请参见Playground
但是,您仍然有一个类型错误:
这是因为右侧的结果可能是
undefined
。如何处理这取决于您。但是,您需要以某种方式处理类型是情节|的事实。未定义
。例如,您必须测试值首先存在:
请参阅操场
You need a
.
See playground
However, you'll still have a type error in:
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 isEpisode | undefined
.For example, you'd have to test the value to see if it exists first:
See playground