typescript - 在 TypeScript 中访问数组项之前检查它是否存在
问题描述
我有数组。
export const routes: {
pathname: string
id: TPageId
access: 'public' | 'authenticated'
}[] = [
{ pathname: '/', id: 'login', access: 'public' },
{ pathname: '/login', id: 'login', access: 'public' },
{ pathname: '/404', id: '404', access: 'public' },
{ pathname: '/users', id: 'users', access: 'authenticated' },
{ pathname: '/runbooks', id: 'runbooks', access: 'authenticated' }
]
我想在尝试将路径复制到这样的变量之前检查是否存在路径......
const pathId = routes.find(route => route.pathname === this.userReloadTarget).id
我怎样才能做到这一点?
解决方案
如果数组中的元素满足提供的测试函数,则 find() 方法返回数组中的第一个值。否则返回未定义。所以在返回 id 之前检查未定义。
const route = routes.find(route => route.pathname === this.userReloadTarget);
const pathId = route!==undefined? route.id: '';
推荐阅读
- ios - 检测用户何时滑过 UICollectionView 的 scrollViewWillBeginDragging 中的某个点?
- javascript - 如何通过javascript在excel中创建对象
- javascript - 显示 JavaScript 对象中的特定元素
- android - 是否可以将原生 Android 子模块和 iOS cocoapods 用于颤振插件?
- json - 在 Typescript 中过滤 Json 数组数据
- machine-learning - 我可以使用树莓派使用预训练的 CNN 模型进行预测吗?
- sql-server - 如何根据可用的 CPU 核心数自动添加 tempdb 数据文件
- bash - $RANDOM 如何在 Unix shell 中工作?看起来像一个变量,但实际上每次调用时都假定不同的值
- javascript - Snowpack & Peerjs: Uncaught ReferenceError: assignment to undeclared variable parcelRequire
- aws-cdk - 使用 python 定义 AWS cdk Fargate 任务 - 如何使用 add_container(secrets=[Mapping[str, Secret]])?