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

标签 javascript arrays regex variables

正则表达式如何存储在 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 循环迭代数组时,循环变量只有当前索引作为字符串,而不是实际值。引用MDN文档Array iteration and for...in ,

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);
    }
    

关于javascript - 在数组中存储正则表达式在 Javascript 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28263709/

相关文章:

regex - 原子团清晰度

javascript - 组合多个事件

javascript - Html5音频ios播放事件

javascript - if 语句简写 - 意外标记;

c - 使用位封装来模拟 c 中 3d 数组的功能

c# - 正则表达式情况...多个具有可变空间的组

Javascript 获取文件主机的主机名

javascript - 在按钮上单击交换正在使用 "document.createElement(' 脚本加载的 JS 文件')

php - 在 codeigniter 中将数组从 Controller 传递到模型

java - 正则表达式(regex)模式匹配