.indexOf()및 .includes()메소드를 사용하여 배열의 요소를 검색하거나 주어진 문자열에서 문자 / 하위 문자열을 검색 할 수 있습니다.
배열에서의 사용
( ECMAScript 사양 링크 )
indexOf사용 항등 비교 반면 includes용도 께 SameValueZero의 알고리즘. 이러한 이유로 다음과 같은 두 가지 차이점이 발생합니다.
에 의해 지적 펠릭스 클링 , 동작은의 경우에는 다르다 NaN.
let arr = [NaN];
arr.indexOf(NaN); // returns -1; meaning NaN is not present
arr.includes(NaN); // returns true
- 의 경우에도 동작이 다릅니다
undefined.
let arr = [ , , ];
arr.indexOf(undefined); // returns -1; meaning undefined is not present
arr.includes(undefined); // returns true
문자열에서의 사용법
( ECMAScript 사양 링크 )
- RegExp를에 전달하면 RegExp를
indexOf문자열로 취급하고 찾은 경우 문자열의 인덱스를 반환합니다. 그러나 RegExp를에 전달 includes하면 예외가 발생합니다.
let str = "javascript";
str.indexOf(/\w/); // returns -1 even though the elements match the regex because /\w/ is treated as string
str.includes(/\w/); // throws TypeError: First argument to String.prototype.includes must not be a regular expression
공연
으로 538ROMEO는 지적 includes보다 (이 첫 번째 인수로 정규식를 확인하기 위해 필요에 대한) 약간 (아주 작은)는 느린 비트 수 있습니다indexOf 있지만, 현실에서,이 많은 차이를 무시할하지 않습니다.
역사
String.prototype.includes()ECMAScript 2015 Array.prototype.includes()에서 도입 되었지만 ECMAScript 2016에서 도입되었습니다. 브라우저 지원과 관련하여 현명하게 사용하십시오.
String.prototype.indexOf()및 Array.prototype.indexOf()인 ECMAScript의 ES5 판에 존재하고 따라서 모든 브라우저에서 지원되지 않습니다.
includes훨씬 더 나쁜 브라우저 지원이 있습니다.