[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf [Back]  [Original]

Array.prototype.indexOf() - JavaScript | MDN

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

View in English Always switch to English

Array.prototype.indexOf()

Baseline Widely available

This feature is well established and works across many devices and browser versions. Its been available across browsers since 2015 7.

Array indexOf() , -1 .

In this article

const beasts = ["ant", "bison", "camel", "duck", "bison"];

console.log(beasts.indexOf("bison"));
// Expected output: 1

// Start from index 2
console.log(beasts.indexOf("bison", 2));
// Expected output: 4

console.log(beasts.indexOf("giraffe"));
// Expected output: -1

js
indexOf(searchElement)
indexOf(searchElement, fromIndex)

searchElement

.

fromIndex Optional

0 , .

  • . , fromIndex < 0, fromIndex + array.length . , .
  • fromIndex < -array.length fromIndex , 0 .
  • fromIndex >= array.length , -1 .

searchElement , -1.

indexOf() searchElement (=== ). NaN , searchElement NaN indexOf() -1 .

indexOf() .

indexOf() . this length .

indexOf()

indexOf() .

js
const array = [2, 9, 9];
array.indexOf(2); // 0
array.indexOf(7); // -1
array.indexOf(9, 2); // 2
array.indexOf(2, -1); // -1
array.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,spinach
updateVegetablesCollection(veggies, "spinach");
// spinach  veggies  .

indexOf()

indexOf() .

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

indexOf()

indexOf() this length 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));
// 0
console.log(Array.prototype.indexOf.call(arrayLike, 5));
// -1

Specification
ECMAScript 2027 LanguageSpecification
# sec-array.prototype.indexof


Web Proxy Viewer  |  New URL  |  Original Page