不是执行嵌套条件,而是更干净,更有效的方法来实现此目的:
请参阅下面的代码。谢谢!
const results = option === 3 ? [...state.nearbyLocations, ...recentSearches] : option === 1 ? [...recentSearches] : [...state.nearbyLocations]
答案 0 :(得分:1)
您可以使用多个扩展元素,具体取决于选项是否为结果提供值:
const results = [
...(option === 3 || option === 2 ? state.nearbyLocations : []),
...(option === 3 || option === 1 ? recentSearches : []),
];
或带有位掩码-因为这实际上是您的选项所匹配的-做
const results = [
...(option & 0b10 ? state.nearbyLocations : []),
...(option & 0b01 ? recentSearches : []),
];
答案 1 :(得分:0)
在这种情况下,最好使用switch语句:
var results = [];
switch (option) {
case 3:
results.push(...state.nearbyLocations, ...recentSearches);
break;
case 1:
results.push(...recentSearches);
break;
case 2:
results.push(...state.nearbyLocations);
break;
}
答案 2 :(得分:-1)
如果您不想嵌套条件,则可以使用Switch Statement。回到当初,它可以保持可读性。
使用您的代码的示例:
switch(option) {
case '1' :
let results = [...recentSearches];
break;
case '2' :
let results = [...state.nearbyLocations];
break;
case '3' :
let results = [...state.nearbyLocations, ...recentSearches];
break;
default:
let results = [];
}