I cannot find the mistake in the following code

function doArray(n){ // test with n > 1000
    var str, i, j,arr=[], cnt=0, q=0, re;
    str = ["one two three","two three four","three four five", "four five one", "five one two"];
    for(i=0; i<n; i++){
        j = Math.round(Math.random()*(str.length-1));
    re =/two/g;
    for(i=0; i<n; i++){
        if(arr[i].indexOf("two") >-1 ){
    alert("found with .test:"+cnt+", and width indexOf:"+q) ;

It is synthesized to find the problem, but it persist.

If you test it by your own, you will see that results are different for 'cnt' and 'q'

Interesting, while debugging, the regexp just misses...

After a little search, I found this thread on SO describing the issue.

In my case, when I used the expression directly, like /two/g.test(arr[i]), instead of store it in a variable, it works.

The g flag isn't relevant to .test() and causes problems.

The following tests give a better indication of what's going on :

function doTests() {
    var i, arr1 = [],
        arr2 = [],
        re1 = /two/g, //bad
        re2 = /two/, //cool
        str = ["one two three", "two three four", "three four five", "four five one", "five one two"];
    for (i = 0; i < 5; i++) {
    alert(arr1.join(', ') + "\n" + arr2.join(', '));

The link in Pritaeas' answer offers an explanation as to why g is problematic.