본문으로 건너뛰기

Array Methods - indexOf, lastIndexOf, includes

Array Methods - indexOf, lastIndexOf, includes

Let's learn about methods for finding specific elements in an array.


indexOf()

The indexOf() method searches the array for a specific element and returns its index. If the element is not found, it returns -1.

Example:

let fruits = ['apple', 'banana', 'cherry', 'apple'];
let index = fruits.indexOf('apple');
console.log(index); // 0

In the example above, "apple" is located at index 0 of the array, hence it prints 0.


lastIndexOf()

As the name suggests, the lastIndexOf() method finds the last index of a specific element in the array. If the element is not found, it returns -1.

Example:

let fruits = ['apple', 'banana', 'cherry', 'apple'];
let lastIndex = fruits.lastIndexOf('apple');
console.log(lastIndex); // 3

"apple" is last found at index 3 of the array, so it prints 3.


includes()

The includes() method checks whether a specific element exists in an array or not. It returns true if it exists, and false if it does not.

Example:

let fruits = ['apple', 'banana', 'cherry'];
let hasApple = fruits.includes('apple');
console.log(hasApple); // true

In the example above, the array contains "apple", so it prints true.