【问题标题】:array.includes returns false using regexarray.includes 使用正则表达式返回 false
【发布时间】:2018-08-22 22:07:09
【问题描述】:

我有这个数组:

array = ['S2B_MSIL1C_20180310T041559_N0206_R090_T46QEK_20180310T075716.SAFE'];

这个正则表达式:

regex = new RegExp('S2B_MSIL1C_20180310T041559_N0206_R090_T46QEK_20180310T075716' + '.SAFE','g');

当我使用 array.includes(regex); 时,false 被返回。我错过了什么吗?

【问题讨论】:

标签: javascript arrays regex


【解决方案1】:

使用Array.some

var yourRegex = /pattern/g ;
var atLeastOneMatches = array.some(e => yourRegex.test(e));

Array.some 在数组中的第一个返回true 后返回true。如果遍历整个数组而没有true,则返回false。

【讨论】:

  • 甚至array.some(yourRegex.test);
【解决方案2】:

RgExps 不用于在数组上搜索,include 方法用于查找所需的对象是否包含在数组中。在这里,您将 Regex 对象传递给您的 include 方法,因此它告诉您数组中没有包含 regex 对象。

您必须执行以下操作之一:

array.includes('S2B_MSIL1C_20180310T041559_N0206_R090_T46QEK_20180310T075716' + '.SAFE');

var yourRegex = /pattern/g ;
for(var i = 0 ; i<arr.length ; i++)
{
    if(yourRegex.test(arr[i]))
    {
        //Founded
        return true;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-31
    • 2011-12-13
    • 2018-03-14
    • 1970-01-01
    • 1970-01-01
    • 2016-07-26
    • 2023-04-06
    • 1970-01-01
    相关资源
    最近更新 更多