[英]How to add items to array based on conditional
Instead of doing a nested conditional, is there a cleaner more efficient way of achieving this: 除了执行嵌套条件之外,还有一种更清洁,更有效的方法来实现此目的:
See below for my code. 请参阅下面的代码。 Thank you! 谢谢!
const results = option === 3 ? [...state.nearbyLocations, ...recentSearches] : option === 1 ? [...recentSearches] : [...state.nearbyLocations]
You could use multiple spread elements that depending on the options contribute a value to the result or not: 您可以使用多个价差元素,具体取决于选项是否为结果提供值:
const results = [
...(option === 3 || option === 2 ? state.nearbyLocations : []),
...(option === 3 || option === 1 ? recentSearches : []),
];
or with bit masks - as that is what your options essentially match - do 或使用位掩码(因为这实际上是您的选项所匹配的)
const results = [
...(option & 0b10 ? state.nearbyLocations : []),
...(option & 0b01 ? recentSearches : []),
];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.