[英]Typescript - Loop through an array backwards with noUncheckedIndexedAccess enabled
在启用了strict
和noUncheckedIndexedAccess
选项的情况下,在 TypeScript 中向后循环数组的最佳方法是什么? 最经典的方法在此配置中不再有效:
function doSomething(i: number): void {
...
}
const arr = [1, 2, 3];
for (let i = arr.length - 1; i >= 0; --i) {
doSomething(arr[i]);
}
它因编译错误而失败:
Argument of type 'number | undefined' is not assignable to parameter of type 'number'.
Type 'undefined' is not assignable to type 'number'.
noUncheckedIndexedAccess
主要用于 objects和数组,如果您要查找的索引可能超过数组的长度。
如果您可以绝对确定该值存在于指定的索引处 - 例如使用像这样的死简单代码(假设您没有改变函数内的数组) - 那么只需在传递它之前断言该值存在:
for (let i = arr.length - 1; i >= 0; --i) {
doSomething(arr[i]!);
}
另一种选择是反转数组,然后对其进行迭代,这在计算上有点昂贵,但更容易一目了然。
arr.reverse().forEach(doSomething);
// no mutation:
[...arr].reverse().forEach(doSomething);
// no mutation:
for (const item of [...arr].reverse()) {
doSomething(item);
}
在可行的情况下,最后三个是我更喜欢的for
循环。
为什么你不像其他人那样做
arr.map(dosonething);
买如果你仍然想这样做,因为你是添加一个如果
if (art[I]!==undefined){
dosonething(art[I]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.