0

My code looks like this:

function testfunc() {

  var exp = /aa/gi;

  var ret = [];

  var test = ['aaa', 'aaa', 'aaa', 'aaa', 'aaa', 'aaa'];

  for (var j = 0; j < test.length; j++) {

    ret.push(exp.test(test[j]));

  }

  console.log(ret);

}

testfunc();

Instead of returning

[true, true, true, true, true, true]

it returns

[true, false, true, false, true, false] 

I don't understand why!

Is there anything wrong in my code?

dippas
  • 58,591
  • 15
  • 114
  • 126
user3716774
  • 431
  • 3
  • 11

1 Answers1

1

you have to remove the g modifier, because of the lastIndex

when matching the next object will start from the last used index instead of 0

function testfunc() {
  var exp = /aa/i;
  var ret = [];
  var test = ['aaa', 'aaa', 'aaa', 'aaa', 'aaa', 'aaa'];
  for (var j = 0; j < test.length; j++) {
    ret.push(exp.test(test[j]));
  }
  console.log(ret);
}
testfunc();
dippas
  • 58,591
  • 15
  • 114
  • 126