在数组中存储正则表达式在 Javascript 中不起作用

Storing regex in an array is not working in Javascript

正则表达式如何存储在 javascript 中。不像通常存储其他 var 类型(如字符串)的方式那样存储。

var regexOne = /^(regex).*$/gm;
var regexTwo = /^(regex).*$/gm;
var regexThree = /^(regex).*$/gm;
var regexFour = /^(regex).*$/gm;
var searchQuery = [regexOne, regexTwo, regexThree, regexFour];

for(query in searchQuery){
    console.dir(query.toString());
}

以上代码打印:

'0'
'1'
'2'
'3'

我怎样才能让它工作。

当你用 for..in 循环迭代数组时,循环变量只有当前索引作为字符串,而不是实际值。在 Array iteration and for...in

上引用 MDN 文档

The for..in statement iterates over the enumerable properties of an object, in arbitrary order.

.... ....

Note: for..in should not be used to iterate over an Array where index order is important.

Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited.

Because the order of iteration is implementation dependent, iterating over an array may not visit elements in a consistent order. Therefore it is better to use a for loop with a numeric index (or Array.forEach or the for...of loop) when iterating over arrays where the order of access is important.

上面的粗体文字说明了一切。因此,您应该使用以下选项之一迭代数组

  1. 正常for循环

    for(var i = 0; i < searchQuery.length; i += 1) {
        console.dir(searchQuery[i]);
    }
    
  2. Array.prototype.forEach函数

    searchQuery.forEach(function(currentRegEx) {
        console.dir(currentRegEx);
    });
    
  3. for...of,循环(注意:这仅适用于实现 ECMAScript 6 的环境)

    for(var currentRegEx of searchQuery) {
        console.dir(currentRegEx);
    }
    

for-in,在 JavaScript 中,循环遍历对象的 可枚举 属性 名称 。它不是用于遍历数组条目或数组索引(尽管有保护措施,它可以用于后者,这就是为什么你会看到 01 等。——那些 属性名称是数组索引)。

有关遍历数组的详细信息,请参阅 this answer,其中包含完整的选项列表和对每个选项的解释。


旁注 1:

您的代码正在成为 The Horror of Implicit Globals 的牺牲品,因为您从未声明 [​​=14=] 变量。 (for-in 构造不会为您声明它。)

旁注 2:

除非您需要 regexOne 和此类变量,否则您可以更简洁地创建正则表达式数组:

var searchQuery = [
    /^(regex).*$/gm,
    /^(regex).*$/gm,
    /^(regex).*$/gm,
    /^(regex).*$/gm
];