javascript - 为什么 Array Prototype 函数不能在每个其他数组函数中工作?
问题描述
我有以下问题,我需要在迭代时从其他数组中获取一些值。
但在 for each 操作中,Array 失去了所有原型函数。
const allCrumbs: BreadCrumb[] = this.createBreadcrumbs(this.activatedRoute.root);
last.url.split('/').forEach((segment: string) => {
if (segment !== '#') {
// This is the part that doesn work within the array
// Edit forgot null check here
const label = allCrumbs.find(value => value.url.endsWith(segment)).label;
// allCrumbs.find(...) is not defined
this.breadCrumbs.push({label: label ? label : segment, url: `/${segment}`});
}
});
// This works just fine
const testlabel = allCrumbs.find(value => value.url.endsWith('test')).label;
当我这样做时,错误:
allCrumbs.find(...) 未定义
出现了。
当我在 Other 数组的范围之外执行相同操作时,它可以正常工作。
有人可以解释这种行为吗?也许给一个解决方案的提示。
非常感谢你:
解决方案
忘了空检查,谢谢。
这现在有效
last.url.split('/').forEach((segment: string) => {
if (segment !== '#') {
const result = allCrumbs.find(value => value.url.endsWith(segment));
this.breadCrumbs.push({label: result ? result.label : segment, url: `/${segment}`});
}
});
真丢人。但是谢谢大家的耐心
解决方案
问题是你.find()
没有根据你的谓词找到任何东西。所以它返回未定义。
相反,期望它可能返回 undefined 并相应地处理。首先尝试找到匹配的值:
const crumb = allCrumbs.find(value => value.url.endsWith(segment));
然后根据您使用的 Angular(以及 Typescript)版本,您可以使用可选链接或三元表达式来获取标签。
角度 >= v9
const label = crumb?.label;
角度 < v9
const label = crumb ? crumb.label : '';
const allCrumbs: BreadCrumb[] = this.createBreadcrumbs(this.activatedRoute.root);
last.url.split('/').forEach((segment: string) => {
if (segment !== '#') {
const crumb = allCrumbs.find(value => value.url.endsWith(segment));
const label = crumb ? crumb.label : '';
this.breadCrumbs.push({
label: label ? label : segment,
url: `/${segment}`
});
}
});