所以我有這個完美運行的代碼,只是它看起來很難看并且占用了大量空間。有沒有辦法減少這段代碼的行數?代碼在這里:
radius: Platform.OS === 'android' ? showMore === 1 ? androidRadius * 2 : showMore === 2 ? androidRadius * 4 : showMore === 3 ? androidRadius * 10 : showMore === 4 ? androidRadius * 25 : showMore === 5 ? androidRadius * 50 : showMore === 6 ? androidRadius * 100 : androidRadius : showMore === 1 ? iosRadius * 2 : showMore === 2 ? iosRadius * 4 : showMore === 3 ? iosRadius * 10 : showMore === 4 ? iosRadius * 25 : showMore === 5 ? iosRadius * 50 : showMore === 6 ? iosRadius * 100 : iosRadius,
uj5u.com熱心網友回復:
使用映射很容易清除這種情況,例如:
const radiusMap = {1: 2, 2: 4, 3: 10, 4: 25, 5: 50, 6: 100};
const platformRadius = Platform.OS === 'android' ? androidRadius: iosRadius;
// finally,
return { radius: radiusMap[platformRadius] || platformRadius };
這將從半徑地圖中獲取半徑,如果在地圖中找不到半徑,也會回傳默認半徑。
uj5u.com熱心網友回復:
對于這些情況,我通常使用物件查找。因此,對于showMore情況,您可以這樣做:-
function getRadius(deviceRadius, showMoreValue){
const showMoreCases = {
1: deviceRadius * 2,
2: deviceRadius * 4,
3: deviceRadius * 10,
4: deviceRadius * 25,
5: deviceRadius * 50,
6: deviceRadius * 100,
}
return showMoreCases[showMoreValue] || deviceRadius;
}
您可以像這樣在第一個條件下使用它:-
radius: Platform.OS === 'android'
? getRadius(androidRadius, showMore)
: getRadius(iosRadius, showMore)
uj5u.com熱心網友回復:
此解決方案是一行代碼。
為了節省空間,它使用陣列而不是鍵/值查找。這在這種情況下有效,因為 showMore 值是連續的。我們從這個索引中減去 2,因為我們只關心范圍 2-7。范圍之外的任何索引都分配有默認半徑。
([2, 4, 10, 25, 50, 100][showMore - 2] || 1) * (Platform.OS === 'android' ? androidRadius : iosRadius)
測驗片段
測驗很重要,因為例如,這里投票最多的答案實際上根本不起作用。如果代碼經過測驗,錯誤就會很明顯。
// TEST
let androidRadius = 100,
iosRadius = 101;
["android", "ios"].forEach(os => {
let Platform = {
OS: os
};
for (let showMore = -2; showMore < 10; showMore ) {
console.log(
"OS: " os,
", showMore: " showMore,
", radius: " ([2, 4, 10, 25, 50, 100][showMore - 2] || 1) * (Platform.OS === 'android' ? androidRadius : iosRadius)
);
}
});
uj5u.com熱心網友回復:
使用switch宣告。這里的例子。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/477326.html
標籤:javascript 反应 if 语句 条件语句 代码清理
上一篇:在下一行標記有結果和沒有結果的行
