Programing

Array.prototype.includes 대 Array.prototype.indexOf

crosscheck 2020. 9. 4. 06:54
반응형

Array.prototype.includes 대 Array.prototype.indexOf


향상된 가독성 외에도 includesover에 대한 이점이 indexOf있습니까? 저와 똑같아 보입니다.

이것의 차이점은 무엇입니까

var x = [1,2,3].indexOf(1) > -1; //true

이?

var y = [1,2,3].includes(1); //true

tl; dr : NaN 은 다르게 취급됩니다.

  • [NaN].indexOf(NaN) > -1 이다 false
  • [NaN].includes(NaN) 이다 true

로부터 제안 :

자극

ECMAScript 배열을 사용할 때 일반적으로 배열에 요소가 포함되어 있는지 확인하는 것이 좋습니다. 이에 대한 일반적인 패턴은 다음과 같습니다.

if (arr.indexOf(el) !== -1) {
    ...
}

다른 다양한 가능성 (예 : arr.indexOf(el) >= 0또는 ~arr.indexOf(el).

이러한 패턴에는 두 가지 문제가 있습니다.

  • 그들은 "당신이 의미하는 바를 말"하지 못합니다. 배열에 요소가 포함되어 있는지 묻는 대신 배열에서 해당 요소의 첫 번째 발생 인덱스가 무엇인지 묻고이를 비교하거나 비트를 비틀 어서 결정합니다. 실제 질문에 대한 답변입니다.
  • Strict Equality Comparison NaNindexOf사용하므로 실패합니다 [NaN].indexOf(NaN) === -1.

제안 된 해결책

Array.prototype.includes위의 패턴을 다음과 같이 재 작성할 수 있는 방법 추가를 제안합니다.

if (arr.includes(el)) {
    ...
}

이것은 Strict Equality Comparison 대신 SameValueZero 비교 알고리즘을 사용하여 사실이된다는 점을 제외하고는 위와 거의 동일한 의미를 갖습니다 [NaN].includes(NaN).

따라서이 제안은 기존 코드에서 볼 수있는 두 가지 문제를 모두 해결합니다.

우리는 추가로 추가 fromIndex유사 매개 변수를, Array.prototype.indexOf그리고 String.prototype.includes일관성을 위해.


추가 정보 :


성능에 대해 궁금하다면 현재 indexOf가 더 빠르지 만,이 JSperf 테스트는 시간 지날 수록 더 빠를 것임을 보여주는 경향 includes()이 있습니다 (더 indexOf최적화 될 것 같습니다).

이럴, 나 또한 쓰기에 선호 if (arr.includes(el)) {}가 명확하고보다 유지 보수 때문에if (arr.indexOf(el) !== -1) {}


.indexOf().includes()메소드를 사용하여 배열의 요소를 검색하거나 주어진 문자열에서 문자 / 하위 문자열을 검색 할 수 있습니다.

배열에서의 사용

( ECMAScript 사양 링크 )

  1. indexOf사용 항등 비교 반면 includes용도 께 SameValueZero의 알고리즘. 이러한 이유로 다음과 같은 두 가지 차이점이 발생합니다.

  2. 에 의해 지적 펠릭스 클링 , 동작은의 경우에는 다르다 NaN.

let arr = [NaN];

arr.indexOf(NaN); // returns -1; meaning NaN is not present
arr.includes(NaN); // returns true
  1. 의 경우에도 동작이 다릅니다 undefined.
let arr = [ , , ];

arr.indexOf(undefined); // returns -1; meaning undefined is not present
arr.includes(undefined); // returns true

문자열에서의 사용법

( ECMAScript 사양 링크 )

  1. 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

공연

As 538ROMEO pointed out, includes may be a little (very tiny) bit slower (for it needs to check for a regex as the first argument) than indexOf but in reality, this doesn't make much difference and is negligible.

History

String.prototype.includes() was introduced in ECMAScript 2015 whereas Array.prototype.includes() was introduced in ECMAScript 2016. With regards to browser support, use them wisely.

String.prototype.indexOf() and Array.prototype.indexOf() are present in ES5 edition of ECMAScript and hence supported by all browsers.


Conceptually you should use indexOf when you want to use the position indexOf just give you to extract the value or operate over the array, i.e using slice, shift or split after you got the position of the element. On the other hand, Use Array.includes only to know if the value is inside the array and not the position because you don't care about it.

참고URL : https://stackoverflow.com/questions/35370222/array-prototype-includes-vs-array-prototype-indexof

반응형