简体   繁体   English

打字稿 - 在启用 noUncheckedIndexedAccess 的情况下向后循环遍历数组

[英]Typescript - Loop through an array backwards with noUncheckedIndexedAccess enabled

What is the best way to loop through an array backwards in TypeScript, with strict and noUncheckedIndexedAccess options enabled?在启用了strictnoUncheckedIndexedAccess选项的情况下,在 TypeScript 中向后循环数组的最佳方法是什么? The most classic approach no longer works well in this config:最经典的方法在此配置中不再有效:

function doSomething(i: number): void {
  ...
}

const arr = [1, 2, 3];
for (let i = arr.length - 1; i >= 0; --i) {
  doSomething(arr[i]);
}

It fails with a compilation error:它因编译错误而失败:

Argument of type 'number | undefined' is not assignable to parameter of type 'number'.
  Type 'undefined' is not assignable to type 'number'.

noUncheckedIndexedAccess is primarily useful for objects , and for arrays if the index you're looking up might be more than the length of the array. noUncheckedIndexedAccess 主要用于 objects和数组,如果您要查找的索引可能超过数组的长度。

If you can be absolutely certain that the value exists at the index specified - such as with dead-simple code like this (assuming you don't mutate the array inside the function) - then simply assert that the value exists before passing it around:如果您可以绝对确定该值存在于指定的索引处 - 例如使用像这样的死简单代码(假设您没有改变函数内的数组) - 那么只需在传递它之前断言该值存在:

for (let i = arr.length - 1; i >= 0; --i) {
  doSomething(arr[i]!);
}

Another option would be to reverse the array, then iterate over it, which is a bit more computationally expensive, but easier to make sense of at a glance.另一种选择是反转数组,然后对其进行迭代,这在计算上有点昂贵,但更容易一目了然。

arr.reverse().forEach(doSomething);
// no mutation:
[...arr].reverse().forEach(doSomething);
// no mutation:
for (const item of [...arr].reverse()) {
    doSomething(item);
}

Those last three are what I'd prefer over a for loop when feasible.在可行的情况下,最后三个是我更喜欢的for循环。

Why you didn't do it as anyone else为什么你不像其他人那样做

arr.map(dosonething);

Buy if you still want to do it as you Is add an if买如果你仍然想这样做,因为你是添加一个如果

if (art[I]!==undefined){
dosonething(art[I]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM