1

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'

3
Contributors
3
Replies
6
Views
5 Years
Discussion Span
Last Post by Airshow
0

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

0

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.

Edited by Airshow

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.