Reputation: 9649
How is regex stored in javascript. Is not stored like the usual way other var types like string is stored.
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());
}
The above code prints:
'0'
'1'
'2'
'3'
How can i get this working.
Upvotes: 0
Views: 143
Reputation: 239473
When you iterate an Array with for..in
loop, the loop variable with have just the current index as string, not the actual value. Quoting MDN documentation on 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.
The bold text above says it all. So, you should iterate arrays with one of the following options
normal for
loop
for(var i = 0; i < searchQuery.length; i += 1) {
console.dir(searchQuery[i]);
}
Array.prototype.forEach
function
searchQuery.forEach(function(currentRegEx) {
console.dir(currentRegEx);
});
for...of
, loop (Note: This will work only in environments which implement ECMAScript 6)
for(var currentRegEx of searchQuery) {
console.dir(currentRegEx);
}
Upvotes: 3
Reputation: 1074355
for-in
, in JavaScript, loops through the enumerable property names of an object. It's not for looping through array entries or array indexes (although with safeguards it can be used for the latter, which is why you're seeing 0
, 1
, etc. — those property names are array indexes).
For details about looping through arrays, see this answer, which has a thorough list of options and explanations of each of them.
Side note 1:
Your code is falling prey to The Horror of Implicit Globals because you never declare the query
variable. (The for-in
construct doesn't declare it for you.)
Side note 2:
Unless you need the regexOne
and such variables, you can create your array of regexes more concisely:
var searchQuery = [
/^(regex).*$/gm,
/^(regex).*$/gm,
/^(regex).*$/gm,
/^(regex).*$/gm
];
Upvotes: 2