【问题标题】:How can I check if it includes more than one things?如何检查它是否包含多个内容?
【发布时间】:2020-08-01 14:21:15
【问题描述】:

有没有办法检查某事物是否包含不止一种事物? 当我这样做时,我的代码不起作用:

if(variable.includes("a" || "e")) {...}

我认为它会因为“||”而工作,但它只适用于“a”,只检查是否有“a”以及是否没有停止代码。

如果有任何语法错误或不好的解释,请见谅。

【问题讨论】:

  • 应该是if(variable.includes("a") || variable.includes("e")) ,你只检查真值。

标签: javascript include


【解决方案1】:

这很可能不是一个很好的解决方案,但如果你的变量是一个数组(例如array = [a, h, a])

那你可以试试:

items=0;
numbers.forEach(function(){ //does a function for every item
items+=1; //will add one for every item
});

然后做:

if (items>1) {
   //code that would run if there is more than one item
}

【讨论】:

    【解决方案2】:

    您需要迭代并检查包含可选值。

    variable.some(v => ["a", "e"].includes(v))
    

    【讨论】:

      【解决方案3】:

      您可以使用以下代码:

      if (['a', 'e'].some(v => variable.includes(v))) {...}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-09-17
        • 2016-03-31
        • 1970-01-01
        • 2012-06-02
        • 2015-12-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多