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));
        arr.push(str[j]);
    }
    re =/two/g;
    for(i=0; i<n; i++){
        if(re.test(arr[i])){
            cnt++;
        };
        if(arr[i].indexOf("two") >-1 ){
            q++;
        }
    }
    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'

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++) {
        arr1.push(re1.test(str[i]));
        arr2.push(re2.test(str[i]));
    }
    alert(arr1.join(', ') + "\n" + arr2.join(', '));
}
doTests();

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.