【问题标题】:Find element in array using regex match without iterating over array使用正则表达式匹配在数组中查找元素而不迭代数组
【发布时间】:2011-08-12 10:05:39
【问题描述】:

我有一个元素数组

["page=4", "sortOrder=asc", "datePosted=all-time"]

使用 javascript 或 jquery 我想找到以 "sortOrder=" 开头的元素的索引。在编译时我不会知道这个元素的完整字符串,只知道"sortOrder=" 部分。

我假设这可以在不需要遍历数组并执行item.match("sortOrder=") 的情况下完成,但也许我错了。

感谢您的帮助。

【问题讨论】:

  • 您确实需要在某个时候迭代数组。不管它是否被框架抽象出来,它仍然需要发生。

标签: javascript jquery arrays


【解决方案1】:

如果您想在与特定正则表达式匹配的数组中获取

...仅获取第一个匹配的,您可以使用find()

const array = ["page=4", "sortOrder=asc", "datePosted=all-time", "sortOrder=desc"];
const match = array.find(value => /^sortOrder=/.test(value));
// match = "sortOrder=asc"

...要获得所有匹配结果的数组,您可以使用filter()

const array = ["page=4", "sortOrder=asc", "datePosted=all-time", "sortOrder=desc"];
const matches = array.filter(value => /^sortOrder=/.test(value));
// matches = ['sortOrder=asc', 'sortOrder=desc'];

...获取第一个匹配的index,可以使用findIndex()

const array = ["page=4", "sortOrder=asc", "datePosted=all-time", "sortOrder=desc"];
const index = array.findIndex(value => /^sortOrder=/.test(value));
// index = 1;

如果你没有使用 ES6,这里是the code in ES5

【讨论】:

    【解决方案2】:

    遗憾的是 indexOf 中没有部分匹配...试试这个,看看它是否有帮助:

    Array.prototype.MatchInArray = function (value) {
    
        var i;
    
        for (i=0; i < this.length; i++) {
    
            if (this[i].match(value)) {
    
               return i;
    
           }
    
       }
    
       return -1;
    
    };
    

    【讨论】:

    • 考虑返回索引 (i) 或 -1(如果未找到),因为这提供了更多信息并且与 Array.indexOf 相当
    • 完成。谢谢@zamnuts!。
    【解决方案3】:

    如果你想在一个数组中找到一个项目,你必须遍历它。如果您的数组按已知顺序排列(例如:它按字母顺序排序),那么您可以在搜索算法中构建一些效率(例如:二叉树搜索),但是除非您在数组中有数千个项目,否则很难将是值得的。在您的情况下,只需遍历数组检查每个项目与您的正则表达式并在找到匹配项时返回。

    【讨论】:

      【解决方案4】:

      来自 ES6 的新 Array.findIndex 函数可以做你想做的事,使用正则表达式而不是遍历数组。

      这里有一个示例:https://jsbin.com/qemeseyeme/edit?js,console

      完整代码示例:

      const arr = ["page=4", "sortOrder=asc", "datePosted=all-time"];
      const str = "sortOrder";
      
      function isStringInArray(str, arr) {
      
        if (arr.findIndex(_strCheck) === -1) return false;
      
        return true;
      
        function _strCheck(el) {
      
          return el.match(str);
        }
      }
      
      console.log(isStringInArray(str, arr));
      

      【讨论】:

        【解决方案5】:

        是的,你错了——你需要迭代。在 ES5 中,有一种查找数组位置的新方法 - Array.indexOf,但在旧版浏览器中不支持此功能,它需要完全匹配而不是部分匹配。

        【讨论】:

        • 嗯,好的,是的,我看到了Array.IndexOf,想知道是否有类似的东西,但部分匹配。可惜没有。
        猜你喜欢
        • 2017-10-16
        • 1970-01-01
        • 2018-03-07
        • 2016-12-08
        • 1970-01-01
        • 2015-05-21
        • 1970-01-01
        • 1970-01-01
        • 2017-11-20
        相关资源
        最近更新 更多