【问题标题】:How to check if an array includes any two particular strings如何检查数组是否包含任何两个特定字符串
【发布时间】:2019-06-15 12:52:45
【问题描述】:
handleDropdown = (dropdown) => {
        dropdown.map(drop => {
            if (drop.value.includes('destroyed') && drop.value.includes('damaged')) {
                console.log("working")
              }
        })
    }

我需要检查数组中是否同时存在“破坏”和“损坏”并返回 true。如果我使用包含检查任何一个条件,它工作正常,我不确定如何检查数组中是否存在两个特定的两个元素。我需要帮助来解决这个问题。提前致谢。

【问题讨论】:

  • 如果drop.value 是数组,这就是你会做的一般方式(希望也对从.map 返回的任何东西做一些事情),你能发布一个minimal reproducible example 以便我们可以看到怎么了?

标签: javascript arrays string include indexof


【解决方案1】:

您可以使用以下内容:

const joined = dropdown.join();
return joined.includes('destroyed') && joined.includes('damaged')

【讨论】:

    【解决方案2】:

    您可以创建一个值数组来检查并使用.every() 来测试它们在您的数据数组中是否存在。

    let data = ['a', 'b', 'destroyed', 'damaged', 'y', 'z'];
    let valuesToCheck = ['destroyed', 'damaged'];
    
    if(valuesToCheck.every(s => data.includes(s))) {
      console.log('It is working');
    }

    【讨论】:

      【解决方案3】:

      你也可以使用indexOf

      let data = ['a', 'b', 'destroyed', 'damaged', 'y', 'z'];
      
      var result = data.indexOf('destroyed')> -1 && data.indexOf('damaged') > -1;
      
      if(result)
        {
          console.log("It is working");
        }

      【讨论】:

        猜你喜欢
        • 2013-01-12
        • 2010-11-16
        • 2016-05-17
        • 1970-01-01
        • 1970-01-01
        • 2014-01-08
        • 1970-01-01
        • 2018-10-12
        • 2015-09-08
        相关资源
        最近更新 更多