[英]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.