简体   繁体   English

如何基于条件将项目添加到数组

[英]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: 除了执行嵌套条件之外,还有一种更清洁,更有效的方法来实现此目的:

  • if option === 3, add both the nearbyLocations and recentSearches object to array 如果选项=== 3,则将附近的位置和最近的搜索对象都添加到数组中
  • if option == 1, add only the recentSearches 如果option == 1,则仅添加最近搜索
  • else (or option === 2), add only nearbyLocations object 否则(或选项=== 2),仅添加nearLocations对象

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 : []),
];

In this situation, it's better to use a switch statement: 在这种情况下,最好使用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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM