在啟用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
是主要有用的對象,並為數組如果你正在尋找了指數可能會超過數組的長度。
如果您可以絕對確定該值存在於指定的索引處 - 例如使用像這樣的死簡單代碼(假設您沒有改變函數內的數組) - 那麼只需在傳遞之前斷言該值存在:
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
在可行的情況下,最後三個是我更喜歡循環的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句