programing

array.prototype.에는 vs.배열.원형.indexOf

cafebook 2023. 9. 25. 23:05
반응형

array.prototype.에는 vs.배열.원형.indexOf

된 것 에 ?includes 이상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).

이러한 패턴은 다음과 같은 두 가지 문제를 나타냅니다.

  • 그들은 배열에 어떤 요소가 포함되어 있는지 묻는 대신, 배열에서 그 요소가 처음으로 나타나는 색인이 무엇인지를 묻고, 그것을 비교하거나 조금씩 돌려 실제 질문에 대한 답을 결정합니다.
  • 그들은 실패합니다.NaN,~하듯이indexOf는 교(엄격한 평등 비교)합니다.[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. ,


자세한 정보:

엄밀히 말하면

NaN를 사용할 때 찾을 수 없습니다.

[NaN].indexOf(NaN) // => -1 (not found)
[NaN].includes(NaN) // => true

includes요소가 발견된 위치의 인덱스를 알고 싶다면 역시 아무 소용이 없습니다.

가독성

arr.indexOf('searchedElement') !== -1가독성과 유지보수성이 떨어집니다.
arr.includes('searchedElement')합니다.boolean.

공연

주제에 대한 이 기사에 따르면 비록 눈에 띄는 차이는 없지만.includes조금 더 느릴 수도 있습니다.

역사

indexOf다보다 훨씬 .includes.

.indexOf()그리고..includes()를 검색하거나 t링을 할 수 .자/subst다.

배열에서의 사용법

(ECMA스크립트 사양 링크)

  1. indexOf엄격한 평등 비교를 사용합니다.includesSameValueZero 알고리즘을 사용합니다.이 때문에 다음과 같은 두 가지 차이점이 발생합니다.

  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

문자열 내 사용

(ECMA스크립트 사양 링크)

. RegExp를 통과한 경우indexOf합니다. RegExp 를나 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

성능

GLAND_PROPRE가 지적했듯이,includes에)다보다 작음) 수 번째 인수로 indexOf하지만 실제로는 별 차이가 없고 무시해도 될 정도입니다.

역사

String.prototype.includes(), ECMAscript 2015면,Array.prototype.includes()는 ECMA트 2016되었습니다에 되었습니다.브라우저 지원에 관해서는 현명하게 사용하세요.

String.prototype.indexOf()그리고.Array.prototype.indexOf()ES5 버전의 ECMAscript에 존재하므로 모든 브라우저에서 지원됩니다.

개념적으로 위치 인덱스를 사용하고자 할 때는 indexOf를 사용해야 합니다. 값을 추출하거나 배열 위에서 연산할 수 있도록 제공합니다. 즉 요소의 위치를 얻은 후 슬라이스, 쉬프트 또는 분할을 사용합니다.반면, Use Array.는 값이 배열 내부에 있는지 여부만 알 수 있고, 값에 상관이 없으므로 위치를 알 수 없습니다.

indexOf()그리고.includes()둘 다 배열에서 요소를 찾는 데 사용될 수 있지만, 각 함수는 서로 다른 반환 값을 산출합니다.

indexOf합니다()-1배열에 요소가 없는 경우 또는 요소가 있는 경우 배열 위치).

includes()값합니다()을 합니다.true아니면false).

인터넷 익스플로러는 다음을 지원하지 않습니다.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#Browser_compatibility

답변과 예시들이 모두 훌륭했습니다. ( 보기에는만에)이다한다는 .includes입니다.trueundefined.

따라서 lse indexOf가 할없는 미정의 값과 NaN 값을 확인하는 데 사용할 수 있도록 예제를 포함합니다.

//Array without undefined values and without NaN values. 
//includes will return false because there are no NaN and undefined values

const myarray = [1,2,3,4]

console.log(myarray.includes(undefined)) //returns false
console.log(myarray.includes(NaN)) //returns false


//Array with undefined values and Nan values.
//includes will find them and return true

const myarray2 = [1,NaN, ,4]

console.log(myarray2.includes(undefined)) //returns true
console.log(myarray2.includes(NaN)) //returns true


console.log(myarray2.indexOf(undefined) > -1) //returns false
console.log(myarray2.indexOf(NaN) > -1) //returns false

요약

  • includes 배열에서 정의되지 않은 값과 NaN 값을 확인하는 데 사용할 수 있습니다.
  • indexOf 배열에서 정의되지 않은 값과 NaN 값을 확인하는 데 사용할 수 없습니다.

indexOf는 배열에 무언가가 있는지 확인하는 오래된 방법이며, 새로운 메서드는 (-1)에 대한 조건을 쓸 필요가 없기 때문에 더 좋습니다. 따라서 부울을 반환하는 include() 메서드를 사용할 때 사용합니다.

array.indexOf('something')      // return index or -1
array.includes('something')     // return true of false

따라서 인덱스를 찾는 데는 첫 번째 방법이 더 낫지만 존재 여부를 확인하는 데는 두 번째 방법이 더 유용합니다.

포함은 문자열과 숫자 사이의 자동 형식 변환을 사용하는 것입니다.indexOf는 그렇지 않습니다.

 
let allGroceries = ['tomato', 'baked bean',];
 
//returns true or false
console.log(allGroceries.includes("tomato")); //uses boolean value to check 

let fruits2 = ["apple", "banana", "orange"];
console.log(fruits2.includes("banana"));
// returns true because banana is in the array



//.indexOf returns the index of the value

console.log(allGroceries.indexOf("tomato"));//returns the index of the value
//returns -1 because tomato is not in the array
//fromIndex
console.log(allGroceries.indexOf("tomato", 2));


() 와 한 중요한 으로 약간 는 () indexOf() 는합니다.indexOf() 으로와 합니다.===연산자는 그러하며, 이 등호 알고리즘은 숫자가 아닌 값을 자신을 포함한 모든 다른 값과 다르게 간주합니다.includes()는 NaN을 자신과 동일한 것으로 간주하는 약간 다른 버전의 동등성을 사용합니다.이는 indexOf()가 배열에서 NaN 값을 감지하지 못하지만 다음을 포함한다는 것을 의미합니다.

let a = [1,true,3,NaN];
a.includes(NaN) // => true
a.indexOf(NaN) // => -1; indexOf can't find NaN

자바스크립트에서: 데이비드 플래너건의 결정적 가이드

언급URL : https://stackoverflow.com/questions/35370222/array-prototype-includes-vs-array-prototype-indexof

반응형