我有一個定義如下的自定義物件(名稱和屬性已被簡化以避免機密資訊泄露):
type T = {
id: number;
title: string;
};
此型別用于創建T
s 串列,如下所示:
const IT: StringMap<T> = {
a: {
id: 0,
title: 'foo',
},
b: {
id: 1,
title: 'bar',
},
c: {
id: 2,
title: 'foobar',
},
}
我需要一種方法能夠T
根據它們的id
. 所以我創建了以下函式:
const getTUsingId = (ts: StringMap<T>, id: number): T => {
Object.values(ts).forEach((t: T) => {
if (t.id === id) {
return t
}
});
// This is as a safeguard to return a default value in case an invalid id is passed
return ts['a']
}
ts['a']
無論出于何種原因,無論id
我傳遞給它什么,這個函式都會回傳。控制臺日志t.id === id
甚至會回傳true
,但它仍然會持續到ts
地圖結束!
非常感謝任何幫助!
uj5u.com熱心網友回復:
return
不會打破你的回圈。您需要使用普通for
回圈:
const getTUsingId = (ts: StringMap<T>, id: number): T => {
for (const t of Object.values(ts)) {
if (t.id === id) {
return t
}
}
return ts['a']
}
uj5u.com熱心網友回復:
forEach 回呼叫于對陣列中的每個元素執行操作,它的 return 不用于終止,您想要的是filter
,find
或常規 for 回圈
Object.values(ts).filter((t: T) => {
return t.id === id;
});
回傳 id 匹配的所有值作為新陣列,如果可能存在多個匹配,您將使用它,然后您需要決議回傳的陣列以確定哪個匹配是正確的
Object.values(ts).find((t: T) => {
return t.id === id;
});
只回傳第一個匹配值
for(const t of Object.values(ts))
if (t.id === id) {
return t
}
});
我的偏好是找到
const getTUsingId = (ts: StringMap<T>, id: number): T => {
return Object.values(ts).find((t: T) => t.id === id) ?? ts['a']
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/505819.html
標籤:javascript 打字稿 功能 for循环