Movatterモバイル変換


[0]ホーム

URL:


  1. 개발자를 위한 웹 기술
  2. JavaScript
  3. JavaScript 참고서
  4. 표준 내장 객체
  5. Array
  6. Array.prototype.indexOf()

This page was translated from English by the community.Learn more and join the MDN Web Docs community.

View in EnglishAlways switch to English

Array.prototype.indexOf()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2015년 7월⁩.

Array 인스턴스의indexOf() 메서드는 배열에서 주어진 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고, 찾을 수 없는 경우 -1을 반환합니다.

시도해 보기

const beasts = ["ant", "bison", "camel", "duck", "bison"];console.log(beasts.indexOf("bison"));// Expected output: 1// Start from index 2console.log(beasts.indexOf("bison", 2));// Expected output: 4console.log(beasts.indexOf("giraffe"));// Expected output: -1

구문

js
indexOf(searchElement)indexOf(searchElement, fromIndex)

매개변수

searchElement

배열에서 위치를 찾을 요소입니다.

fromIndexOptional

검색을 시작할 0 기반 인덱스로,정수로 변환됩니다.

  • 음수 인덱스는 배열의 끝부터 거꾸로 셉니다. 즉,fromIndex < 0이면,fromIndex + array.length가 사용됩니다. 그러나, 이 경우에도 배열은 여전히 앞에서 뒤로 검색됩니다.
  • fromIndex < -array.length이거나fromIndex가 생략되면,0이 사용되어 전체 배열이 검색됩니다.
  • fromIndex >= array.length 이면, 배열은 검색되지 않고-1이 반환됩니다.

반환 값

배열에서searchElement의 첫 번째 인덱스이고, 찾을 수 없으면-1입니다.

설명

indexOf() 메서드는엄격한 동등성을 사용하여 배열의 요소와searchElement를 비교합니다(=== 연산자가 사용하는 것과 동일한 알고리즘).NaN 값은 절대 동일하게 비교되지 않으므로,searchElementNaN인 경우indexOf()는 항상-1을 반환합니다.

indexOf() 메서드는희소 배열의 빈 슬롯을 건너뜁니다.

indexOf() 메서드는범용입니다.this 값에는length 속성과 정수 키 속성만 있을 것으로 예상합니다.

예제

indexOf() 사용하기

다음 예제는indexOf()를 사용하여 배열에서 값을 찾습니다.

js
const array = [2, 9, 9];array.indexOf(2); // 0array.indexOf(7); // -1array.indexOf(9, 2); // 2array.indexOf(2, -1); // -1array.indexOf(2, -3); // 0

indexOf()를 사용하여NaN을 검색할 수 없습니다.

js
const array = [NaN];array.indexOf(NaN); // -1

요소가 나타난 모든 위치 찾기

js
const indices = [];const array = ["a", "b", "a", "c", "a", "d"];const element = "a";let idx = array.indexOf(element);while (idx !== -1) {  indices.push(idx);  idx = array.indexOf(element, idx + 1);}console.log(indices);// [0, 2, 4]

배열에 요소가 있는지 확인하고 배열 업데이트하기

js
function updateVegetablesCollection(veggies, veggie) {  if (veggies.indexOf(veggie) === -1) {    veggies.push(veggie);    console.log(`새로운 veggies 컬력션은 ${veggies}`);  } else {    console.log(`${veggie}는 이미 veggies 컬렉션에 존재합니다.`);  }}const veggies = ["potato", "tomato", "chillies", "green-pepper"];updateVegetablesCollection(veggies, "spinach");// 새로운 veggies 컬력션은 potato,tomato,chillies,green-pepper,spinachupdateVegetablesCollection(veggies, "spinach");// spinach는 이미 veggies 컬렉션에 존재합니다.

희소배열에 indexOf() 사용하기

indexOf()를 사용하여 희소 배열에서 빈 슬롯을 검색할 수 없습니다.

js
console.log([1, , 3].indexOf(undefined)); // -1

배열이 아닌 객체에서 indexOf() 호출하기

indexOf() 메서드는thislength 속성을 읽은 다음 키가length보다 작은 음수가 아닌 정수인 각 속성에 접근합니다.

js
const arrayLike = {  length: 3,  0: 2,  1: 3,  2: 4,  3: 5, // length가 3이므로 indexOf()에서 무시됩니다.};console.log(Array.prototype.indexOf.call(arrayLike, 2));// 0console.log(Array.prototype.indexOf.call(arrayLike, 5));// -1

명세서

Specification
ECMAScript® 2026 Language Specification
# sec-array.prototype.indexof

브라우저 호환성

같이 보기

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp