我想合并這些 if 陳述句以使其盡可能高效,同時仍然能夠單獨執行案例 1,單獨執行案例 2,同時執行案例 1 和案例 2,而不是案例 1 和案例 2。有沒有辦法做到這一點?
if(x >= 100 && y < 100){
return(
<View>
<Text>
this is case 1
</Text>
</View>
)}
if(x < 100 && y >= 100){
return(
<View>
<Text>
this is case 2
</Text>
</View>
)}
if(x < 100 && y < 100){
return(
<View>
<Text>
this is case 1
</Text>
</View>
<View>
<Text>
this is case 2
</Text>
</View>
)}
if(x >= && y >= 100){
return(
<View>
<Text>
this is case 4
</Text>
</View>
)}
uj5u.com熱心網友回復:
將您的回傳值放在一個變數中,您可以為每種情況連接該變數。
retval = '';
if (y < 100) {
retval =
<View>
<Text>
this is case 1
</Text>
</View>
;
}
if (x < 100) {
retval =
<View>
<Text>
this is case 2
</Text>
</View>
;
}
if (retval == '') {
// neither case
return(
<View>
<Text>
this is case 4
</Text>
</View>
);
} else {
return retval;
}
uj5u.com熱心網友回復:
試試這個:
const el1 = (
<View>
<Text>
this is case 1
</Text>
</View>
)
const el2 = (
<View>
<Text>
this is case 2
</Text>
</View>
)
...
const conditions = {
el1,
el2,
...
}
if (x >= 100 && y < 100)
return conditions.el1
else if (x < 100 && y >= 100)
return conditions.el2
else if (x < 100 && y < 100)
return conditions.el1 conditions.el2
else
return conditions.default || ''
uj5u.com熱心網友回復:
您可以收集所需的字串并回傳格式化的集合或案例四。
const take = [];
if (x < 100) take.push('this is case 2');
if (y < 100) take.push('this is case 1');
return take.length
? take.map(/* your formatting */)
: 'this is case 4';
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/426582.html
標籤:javascript if 语句
上一篇:如何設定一個函式以在javascript中運行每個螢屏更新?[復制]
下一篇:根據元素將陣列組合成物件
