2016-07-02 1 views
0

내 코드는 다음과 같습니다.test()의 결과가 변경되는 이유는 무엇입니까?

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();

대신 내가 왜

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

이해하지 못하는 반환

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

를 반환하는!

내 코드에 이상이 있습니까?

+4

remo0ve의 g 수정 대신 마지막으로 사용 된 인덱스에서 시작하기 때문에 lastIndex

의, g 수정을 제거해야 –

+1

[이유 - 왜 - regexp -와 - 글로벌 - 플래그 - 자바 스크립트 - 옳지 - 결과] (http://stackoverflow.com/questions/1520800/why-regexp)의 중복 -with-global-flag-in-javascript-wrong-results) – ryeballar

+0

대단히 고마워요! 그 게시물 정말 도움이! – user3716774

답변

1

당신이 때 다음 개체를 일치하는 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();

관련 문제