首页 > 解决方案 > 在 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

我怎样才能做到这一点?

标签: typescript

解决方案


如果数组中的元素满足提供的测试函数,则 find() 方法返回数组中的第一个值。否则返回未定义。所以在返回 id 之前检查未定义。

const route = routes.find(route => route.pathname === this.userReloadTarget);
const pathId = route!==undefined? route.id: '';

推荐阅读