正则表达式如何存储在 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 anArray
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 (orArray.forEach
or thefor...of
loop) when iterating over arrays where the order of access is important.
上面的粗体文字说明了一切。因此,您应该使用以下选项之一迭代数组
正常的
for
循环for(var i = 0; i < searchQuery.length; i += 1) { console.dir(searchQuery[i]); }
-
searchQuery.forEach(function(currentRegEx) { console.dir(currentRegEx); });
for...of
, 循环(注意:这仅适用于实现 ECMAScript 6 的环境)for(var currentRegEx of searchQuery) { console.dir(currentRegEx); }
关于javascript - 在数组中存储正则表达式在 Javascript 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28263709/